我想使用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;
}
}
答案 0 :(得分:1)
您需要从restoreit
定义中删除 const 。恢复时,f_
映射被修改-您只能在非const成员函数中进行此操作。
void restoreit(const std::string &name)
{
std::ifstream ifs(name);
boost::archive::text_iarchive ia(ifs);
ia >> *this;
}