[英]How to serialize a CString using boost
我正在嘗試使用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):錯誤C2039:'serialize':不是'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。
如果要使用類,則只能使用save
和load
,可以將BOOST_SERIALIZATION_SPLIT_MEMBER()添加到其定義中。 由於無法對字符串執行此操作,因此需要使用serialize
方法來實現Boost序列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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.