gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:38:47 24 4
gpt4 key购买 nike

假设我正在使用 boost 将 map 序列化为 XML 存档。该 map 的类型为 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< long, CMyObject > 但需要更改为 std::map< std::string, CMyObject >。处理这个问题最干净的方法是什么?

最佳答案

嗯, split serialize into save/load , bump 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;
}

关于C++ boost 序列化 - 如何替换存档中的字段类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16246087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com