【发布时间】:2015-06-02 11:32:34
【问题描述】:
我已尝试为我的非成员 serialize() 函数提供类 A 的 getter,因为从成员访问是私有的。
template<typename T>
class A
{
public:
A(const T& id) : m_id(id) {}
T& getRef() { return m_id; } // not giving good results
T getId() { return m_id; } // not giving good results
const T& getRef() const { return m_id; } // not giving good results
private: // I would like to keep it private
T m_id;
}
namespace boost { namespace serialization {
template<class Archive,typename T>
void serialize(Archive &ar, A &a, const unsigned int version)
{
// ar &BOOST_SERIALIZATION_NVP(a.m_id); // I would like to avoid that it works if m_id is public
ar &BOOST_SERIALIZATION_NVP(a.GetRef()); // I want this !
}
}}
// and later I use
std::ofstream ofs("test.xml");
boost::archive::xml_oarchive oa(ofs);
A<int> a(42);
oa << BOOST_SERIALIZATION_NVP(a);
不幸的是,当我尝试使用吸气剂GetRef()或GetId()时,执行一直告诉我uncaught exception of type boost::archive::xml_archive_exception - Invalid XML tag name。
如果我在公开时直接访问m_id,效果会很好。
有什么好的方法吗?
【问题讨论】:
标签: c++ serialization boost boost-serialization