2011-01-26 20 views
1

我想使用boost ::序列化來替換實現它自己的序列化方法的現有項目的一部分,但並不是那麼好。 但是,我正面臨一些問題,因爲應用程序使用MFC。我試圖序列化的CString如下如何序列化一個CString使用boost

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 \提升\序列\ access.hpp(118): 錯誤C2039: '序列化':是不是 成員 '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這樣的數組?

回答

2

如果你正在使用一個類,你可以只使用saveload,你可以添加BOOST_SERIALIZATION_SPLIT_MEMBER()來定義。既然你不能這樣做,對於字符串,你需要實現一個serialize方法方面加速系列化:

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); 
} 
+0

還要注意,根據您的編譯器版本,您可能需要將'serialize','save'和'load'這三個'boost :: serialization'命名空間。 (用'namespace boost {命名空間序列化{...}}'環繞它們。) –

4

您需要使用BOOST_SERIALIZATION_SPLIT_FREE(T),其中T是類型名(如CString或CArray),以便生成將序列化分解爲加載和保存的代碼,非侵入性。對於一個類中(即侵入式),這相當於BOOST_SERIALIZATION_SPLIT_MEMBER。

相關問題