C ++ boost序列化 - 如何替换归档中的字段类型

时间:2013-04-26 22:21:19

标签: c++ serialization boost

假设我使用boost将地图序列化为XML存档。该地图的类型为std :: map< long,CMyObject>。我意识到我需要使用这种类型:std :: map< std :: string,CMyObject>。在这种情况下,我将如何处理向后兼容性?这就是我的序列化方法现在的样子:

    template<class Archive>
    void serialize(Archive & ar, const unsigned int file_version)
    {
        ar & BOOST_SERIALIZATION_NVP(m_MyMap);
    }
    void serialize ( std::ostream &out ) const
    {
        boost::archive::xml_oarchive oa ( out );
        oa << boost::serialization::make_nvp ( "MyArchive.xml", *this );
    }
    void serialize ( std::istream &in )
    {
        boost::archive::xml_iarchive ia ( in );
        ia >> boost::serialization::make_nvp ( "MyArchive.xml", *this );
    }

m_MyMap目前的类型为std :: map&lt; long,CMyObject&gt;但需要更改为std :: map&lt; std :: string,CMyObject&gt;。处理这个问题的最简洁方法是什么?

1 个答案:

答案 0 :(得分:1)

那么, split serialize into save/loadbump the version, 和

template<class Archive>
void load (Archive & ar, unsigned version) {
  if (version < 1) {
    std::map<long, CMyObject> tmp; ar & tmp;
    for (auto& en: tmp) m_MyMap[std::to_string(en.first)] = en.second;
  } else ar & m_MyMap;
}