我想使用 boost 序列化来序列化/反序列化类实例中的数据。这个想法是类应该封装数据,以及序列化和反序列化的细节。这适用于使用 ar << this
进行序列化,但使用 ar >> this
的可比反序列化给出编译错误
error: cannot bind non-const lvalue reference of type ‘const q*&’ to an rvalue of type ‘const q*’
以下是我的不可编译的完整工作代码 restoreit
函数注释掉了。这显然是对我的真实代码的简化,但问题是一样的。如何将反序列化方法封装到我的类中?
#include <fstream>
#include <iostream>
#include <map>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
class q
{
public:
q() : f_() { }
void setup() { f_.insert(std::make_pair(18,10)); }
int getcount() { return f_.size(); }
void storeit(const std::string &name)
{
std::ofstream ofs(name);
boost::archive::text_oarchive ar(ofs);
ar << this;
}
void restoreit(const std::string &name) const
{
std::ifstream ifs(name);
boost::archive::text_iarchive ia(ifs);
// The following line gives the error: cannot bind non-const lvalue reference of type ‘const q*&’ to an rvalue of type ‘const q*’
// ia >> this;
}
private:
std::map<int,int> f_;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & f_;
}
};
int main(void)
{
const std::string name = "/tmp/blah";
q foo;
foo.setup();
foo.storeit(name);
q foo2;
// I want to use foo2.restore(name) here
{
std::ifstream ifs(name);
boost::archive::text_iarchive ia(ifs);
ia >> foo2;
}
}
最佳答案
您需要从 restoreit
定义中删除 const。恢复时,正在修改 f_
映射 - 您只能在非常量成员函数中执行此操作。
void restoreit(const std::string &name)
{
std::ifstream ifs(name);
boost::archive::text_iarchive ia(ifs);
ia >> *this;
}
关于c++ - 使用引导序列化从成员函数反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348830/