我正在使用boost进行序列化:
bool saveParams(std::string filename)
{
using boost::serialization::make_nvp;
std::ofstream ofs(filename.c_str());
if(ofs.is_open() == false) return false;
boost::archive::xml_oarchive xml(ofs);
xml << make_nvp("Param1", param1value);
xml << make_nvp("Param2", param2value);
xml << make_nvp("Param3", param3value);
xml << make_nvp("Param4", param4value);
}
加载完成:
bool loadParams(std::string filename)
{
using boost::serialization::make_nvp;
std::ifstream ifs(filename.c_str());
if(ifs.is_open() == false) return false;
boost::archive::xml_iarchive xml(ifs);
xml >> BOOST_SERIALIZATION_NVP(param1value);
xml >> BOOST_SERIALIZATION_NVP(param2value);
xml >> BOOST_SERIALIZATION_NVP(param3value);
xml >> BOOST_SERIALIZATION_NVP(param4value);
}
现在我要添加Param5。 如何添加aditional版本信息并在加载时处理?我在docs中找到了在使用BOOST_CLASS_VERSION(serialized_class, version)
序列化时如何执行此操作。
答案 0 :(得分:0)
所以我将把我丑陋的解决方案作为答案。当出现更好的解决方案时,我会接受它。
我已经处理了例外情况:
bool loadParams(std::string filename)
{
using boost::serialization::make_nvp;
std::ifstream ifs(filename.c_str());
if(ifs.is_open() == false) return false;
boost::archive::xml_iarchive xml(ifs);
try
{
xml >> BOOST_SERIALIZATION_NVP(param1value);
xml >> BOOST_SERIALIZATION_NVP(param2value);
xml >> BOOST_SERIALIZATION_NVP(param3value);
xml >> BOOST_SERIALIZATION_NVP(param4value);
}
catch(boost::archive::archive_exception e)
{
qDebug()<<"Exception: "<<e.what();
}
try
{
xml >> BOOST_SERIALIZATION_NVP(newParam);
}
catch(boost::archive::archive_exception e)
{
qDebug()<<"New version!";
}
}
答案 1 :(得分:0)
只需为版本创建一个整数并首先将其序列化。
2-1
首次加载时读取版本并使用
int param_ver = 1;
xml << BOOST_SERIALIZATION_NVP(param_ver);
xml << BOOST_SERIALIZATION_NVP(param1value);
xml << BOOST_SERIALIZATION_NVP(param2value);
xml << BOOST_SERIALIZATION_NVP(param3value);
xml << BOOST_SERIALIZATION_NVP(param4value);
xml << BOOST_SERIALIZATION_NVP(param5value);