使用 boost::serialization 的序列化树结构
我必须在程序中序列化 libkdtree++,树结构简要描述如下:
struct _Node_base {
_Node_base * _M_parent, *_M_left, * _M_right;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar & _M_left & _M_right;
}
}
template<typename V>
struct _Node : public _Node_base {
typedef V value_type;
value_type value;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar.register_type(static_cast<_Node*>(NULL));
ar & boost::serialization::base_object<_Node_base>(*this);
ar & value;
}
}
struct Tree {
_Node * root;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar & root;
}
}
该程序报告“流错误”。 但从“序列化文件”来看,它缺少根的子节点的值字段。因此我认为 BaseNode 有可能序列化了 _M_left 和 _M_right 指针。然而,由于 _Node_base 不知道 _Node 的值类型,因此看起来很难将“ar.register_type”添加到 _Node_base.serialize() 中。
I have to serialize libkdtree++ in my program, the tree structures are briefly described as following:
struct _Node_base {
_Node_base * _M_parent, *_M_left, * _M_right;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar & _M_left & _M_right;
}
}
template<typename V>
struct _Node : public _Node_base {
typedef V value_type;
value_type value;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar.register_type(static_cast<_Node*>(NULL));
ar & boost::serialization::base_object<_Node_base>(*this);
ar & value;
}
}
struct Tree {
_Node * root;
template<Archive>
serialize(Archive &ar, const unsigned int version) {
ar & root;
}
}
This program reports "stream error".
But from the "serailzed file", it lacks the value fields for the children nodes of roots. Thus I think it is possible that BaseNode serialized _M_left and _M_right pointer. However since _Node_base have no idea about the value type of _Node, so it looks hard to add "ar.register_type" to _Node_base.serialize().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
point_conflict 异常 文档 指出(原文如此)
:认为冲突发生在每个由
BaseNode::serialize
中的 ptr 序列化以及通过Node::serialize< 中的直接对象
*Node
表达式序列化的情况下。 /代码>。但是,由于base_object
函数采用引用而不是 ptr,我不确定如何避免这种情况。一种可能性是不序列化
parent
ptr。相反,在反序列化之后,遍历树并修复父指针以指向节点父节点。例如,将以下方法添加到 BaseNode :然后只需调用
root->fix ()
The pointer_conflict exception documentation states (sic):
I think the conflict occurs where each is serialised by a ptr in
BaseNode::serialize
and via the direct object, the*Node
expression, inNode::serialize
. However since thebase_object
function takes a reference and not a ptr I'm not sure how you would avoid this.One possibility is to not serialize the
parent
ptr. Instead, after deserialization, do a walk of the tree and fix up the parent ptrs to point to the node parent. E.g. add the following method to BaseNode :Then just call
root->fix ()
libkdtree++ & 的以下解决方案boost::serialization 似乎有效:
The following solution for libkdtree++ & boost::serialization seems work: