1

我正在尝试使用 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而有一些序列化。

现在我想知道,我能做什么?有什么解决方法吗?我试图避免将 CStrings 重新定义为 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 之类的数组?

4

2 回答 2

4

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

于 2011-01-26T02:03:30.940 回答
2

您只能使用save并且load如果您正在使用一个类,您可以将 BOOST_SERIALIZATION_SPLIT_MEMBER() 添加到定义中。由于您不能对字符串执行此操作,因此您需要根据serialize方法实现 Boost 序列化:

template<class Archive>
void serialize(Archive & ar, CString & s, const unsigned int version)
{
    std::string ss(s);
    ar & ss;
    s = ss.c_str;
}

这效率较低,但至少应该编译。

编辑:实际上,您可以拆分免费功能,但您需要将其与保存和加载功能一起添加:

#include <boost/serialization/split_free.hpp>

template<class Archive>
inline void serialize(Archive & ar, CString & s, const unsigned int file_version) {
    split_free(ar, s, file_version); 
}
于 2011-01-26T01:56:44.747 回答