假设我有一个类A
,其中包含一个私有成员B const * p
,可以通过公共函数B const& A::get()
访问。如何序列化函数A使用boost save_construct_data
和load_construct_data
函数?
以下是我的包含尝试(请注意,此示例说明了问题本身,而不是原因我使用此get
函数的原因):
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <fstream>
class B
{
public:
int a;
//////////////////////////////////
// Boost Serialization:
//
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar,const unsigned int file_version)
{
ar & a;
}
};
class A
{
public:
A(B const * p) : p(p) {}
B const& get() const {return *p;}
private:
B const * p;
void A::Save(char * const filename);
static A * const Load(char * const filename);
//////////////////////////////////
// Boost Serialization:
//
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar,const unsigned int file_version){}
};
namespace boost
{
namespace serialization
{
template<class Archive>
inline void save_construct_data(
Archive & ar, A const * t, unsigned const int file_version
)
{
ar << &t->get();
}
template<class Archive>
inline void load_construct_data(
Archive & ar, A * t, const unsigned int file_version
)
{
B const * p;
ar >> p;
::new(t) A(p);
}
}
}
// save the world to a file:
void A::Save(char * const filename)
{
// create and open a character archive for output
std::ofstream ofs(filename);
// save data to archive
{
boost::archive::text_oarchive oa(ofs);
// write the pointer to file
oa << this;
}
}
// load world from file
A * const A::Load(char * const filename)
{
A * a;
// create and open an archive for input
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
// read class pointer from archive
ia >> a;
return a;
}
int main()
{
}
错误是:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const B *' (or there is no acceptable conversion)
答案 0 :(得分:2)
您无法序列化临时(AFAICT即Boost限制)。
B const * p = &t->get();
ar << p;