c++ - 如何使用 boost 序列化 CString

标签 c++ boost mfc cstring boost-serialization

我正在尝试使用 boost::serialization 来替换现有项目的一部分,该项目实现了自己的序列化方法但效果不是很好。 但是,由于应用程序使用 MFC,我遇到了一些问题。我尝试按如下方式序列化 CString

template<class Archive>
void save(Archive & ar, CString & s, const unsigned int version) {  
  using boost::serialization::make_nvp;
  const std::basic_string<TCHAR> ss((LPCTSTR)s);
  ar & make_nvp("String", ss);
}
template<class Archive>
void load(Archive & ar, CString & s, const unsigned int version) {  
  using boost::serialization::make_nvp;
  std::string ss;
  ar & make_nvp("String",ss);
  s = ss.c_str;
}

但是我遇到了一些错误

boost_1_45_0\boost\serialization\access.hpp(118): error C2039: 'serialize' : is not a member of 'ATL::CStringT'

在 access.hpp 中它说

// note: if you get a compile time error here with a
// message something like:
// cannot convert parameter 1 from <file type 1> to <file type 2 &>
// a likely possible cause is that the class T contains a 
// serialize function - but that serialize function isn't 
// a template and corresponds to a file type different than
// the class Archive.  To resolve this, don't include an
// archive type other than that for which the serialization
// function is defined!!!

所以我想 CString 由于 MFC 而有一些序列化。

现在我想知道,我能做什么?有什么解决方法吗? 我试图避免将 CString 重新定义为 std:string,因为它们太多了,这意味着要重新做整个项目。

此外,我想序列化一个 CArray,但我遇到了相同类型的错误,即序列化不是 CArray 的成员。

编辑: 通过添加

修复了 CString 问题
template<class Archive>
inline void serialize(Archive & ar, CString & s, const unsigned int file_version) {
    split_free(ar, s, file_version); 
}

我不知道为什么宏不起作用。但是,我仍然面临 CArray 的问题。我尝试了一个简单的解决方案

ar & make_nvp("CArray",myCArray); 

但这不会创建任何 XML。然后我尝试像这样遍历数组

for(int i=0; i < myCArray.GetCount(); i++) {
  MyClass* m = (MyClass*) myCArray.GetAt(i);      
  ar & BOOST_SERIALIZATION_NVP(m);
}

但这并不是调用类的序列化。是否有任何直接的方法来序列化数组,例如 Boost 示例中的 std::vector 或 std::list?

最佳答案

您需要使用 BOOST_SERIALIZATION_SPLIT_FREE(T),其中 T 是类型名称(如 CString 或 CArray),以便生成将序列化拆分为加载和保存的代码,非侵入式。这相当于类内的 BOOST_SERIALIZATION_SPLIT_MEMBER(即侵入式)。

关于c++ - 如何使用 boost 序列化 CString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4800667/

相关文章:

c++ - MFC 多线程 : AfxBeginThread vs Boost. 线程?

visual-c++ - 遍历 MFC CComboBox 的项目

c++ - `volatile` 是否允许使用 union 进行类型双关?

c++ - 此人如何使用 Microsoft Paint 编码 "Hello World"?

c++ - 如何转换boost::fusion::vector的类型?

c++ - boost::copy_graph 的vertex_copy 是如何工作的?

c++ - QTableWidget 到多个文件

c++ - 我是否应该将所有 .o 文件放入库中?

c++ - Boost::spirit 属性类型不崩溃

c++ - 是否可以将 COM 智能指针与 CList 集合一起使用