2010-07-19 43 views
2

下面的序列化示例來自boost mailing list,它與我想要做的幾乎相同。但是,我已經更改了存檔,以便它將序列化爲XML。如果我序列化爲二進制,編譯不會失敗,但在序列化爲xml時失敗。編譯在basic_xml_oarchive.hpp未能在下面的方法:使用boost :: serialization序列化對象映射到xml

// boost code where compile fails 
template<class T> 
void save_override(T & t, BOOST_PFTO int) 
{ 
    // If your program fails to compile here, its most likely due to 
    // not specifying an nvp wrapper around the variable to 
    // be serialized. 
    BOOST_MPL_ASSERT((serialization::is_wrapper<T>)); 
    this->detail_common_oarchive::save_override(t, 0); 
} 

看來我做得還不夠,讓std::map<int, CSomeData>對象序列化,就如何解決這一問題的任何想法?


我的序列化的實現:

#include <boost/archive/xml_oarchive.hpp> 
#include <boost/archive/xml_iarchive.hpp> 
#include <boost/serialization/map.hpp> 
#include <fstream> 
#include <string> 
#include <map> 

using namespace std; 

// This is a test class to use as the map data. 
class CSomeData { 
    public: 
     CSomeData(){}; 
     CSomeData(float f0, string str0) 
     { 
      m_f0 = f0; 
      m_str0 = str0; 
     } 

     float m_f0; 
     string m_str0; 

    private: 
     friend class boost::serialization::access; 

     template<class Archive> 
     void serialize(Archive &ar, const unsigned int version) 
     { 
      ar & m_f0; 
      ar & m_str0; 
     } 
}; 

// This is the class we really want to try serializing. 
class CTest { 
    public: 
     CTest(){}; 
     CTest(int nNumber) 
     { 
      m_nNumber = nNumber; 

      // Fill with some dummy data. 
      m_mTst.insert(make_pair(0, CSomeData(0.23f, "hi hi hi"))); 
      m_mTst.insert(make_pair(1, CSomeData(7.65f, "second one"))); 
      m_mTst.insert(make_pair(2, CSomeData(9.23f, "third one"))); 
      m_mTst.insert(make_pair(3, CSomeData(5.6766, "chosen one"))); 
     } 
     ~CTest(){}; 

     save() 
     { 
      std::ofstream ofs("filename"); 

      // Write class instance to archive. Writing seems to work ok. 
      boost::archive::xml_oarchive oa(ofs); 
      oa << BOOST_SERIALIZATION_NVP(*this); 
     } 

     int m_nNumber; 

    private: 
     map<int, CSomeData> m_mTst; 

     friend class boost::serialization::access; 

     template<class Archive> 
     void serialize(Archive &ar, const unsigned int version) 
     { 
      ar & m_nNumber; 
      ar & m_mTst; 
     } 
}; 
+0

我想我的問題是Codegear不支持序列化。 http://blogs.embarcadero.com/ddean/2009/09/23/34847 – Seth 2010-07-19 07:52:26

回答

4

我相信你需要的會員提供用於XML序列化的一個名牌。這指定了要在XML中使用的元素名稱。即使用這樣的:(在這種情況下更好)

ar & BOOST_SERIALIZATION_NVP(m_f0); 

或:

ar & make_nvp("field0", my_f0); 

的標籤將用於二進制序列被忽略。更多細節在這裏:

http://www.boost.org/doc/libs/1_43_0/libs/serialization/doc/wrappers.html

+0

這沒有奏效,我已經在使用'BOOST_SERIALIZATION_NVP'宏 – Seth 2010-07-19 08:02:50

+0

CSomeData :: serialize()不在上面的代碼中。 – 2010-07-19 08:08:55

+0

你是對的!這也編譯了。 – Seth 2010-07-19 08:25:02