Boost Serialization 如何利用 operator&来实现存档/序列化?



Boost序列化是如何工作的?

特别是,Boost Serialization似乎使用了operator &

如何定义如下这样的函数

template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & degrees;
ar & minutes;
ar & seconds;
}

结合friend class boost::serialization::access;

是否允许调用以下函数?

std::ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);
oa << g;

示例取自文件。

您有boost::serialization::access作为相关类型的好友所在地,这将向相关方公开serialise

类似于:

namespace boost::archive {
class access {
protected:
template <typename T, typename Archive>
void serialise(T & t, Archive & a, int version) {
t.serialise(a, version);
}
};
}

归档类型将继承自boost::serialization::access,还实现各种operator &,包括调用serialise的catch-all模板。例如,写入std::ostream

namespace boost::archive {
class oarchive : access {
public:
void operator &(int i) { os << i; }
/* other overloads for things that you can os << into */
template <typename T>
void operator &(T & t) { serialise(t, *this, version); }
private:
std::ostream & os;
int version = /* determine version somehow */;
}
}

或用于从std::istream读取

namespace boost::archive {
class iarchive : access {
public:
void operator &(int i) { is >> i; }
/* other overloads for things that you can is >> out of */
template <typename T>
void operator &(T & t) { serialise(t, *this, version); }
private:
std::istream & is;
int version = /* determine version somehow */;
}
}

最新更新