Byz*_*ian 12 c++ serialization boost
我目前正在开发一个软件项目,该项目需要对象持久性作为其实现的一部分.升级序列化库乍一看似乎完全适合这项工作,但现在我已经尝试使用它,我开始质疑它的整体设计.
库希望用户为用户想要序列化的每个类定义序列化方法.
class Object
{
private:
int member;
public:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & member;
}
};
Run Code Online (Sandbox Code Playgroud)
如果有问题的类具有属于其他第三方库和API的成员对象,则会出现问题.即使我碰巧使用的那些都在zlib许可下可用,修改库头只是感觉不对.
但是开发人员已经想到了这一点,并提供了一个非侵入式版本,允许在不修改它们的情况下向类添加序列化.辉煌.
template<class Archive>
void serialize(Archive & ar, Object& o, const unsigned int version)
{
ar & o.member;
}
Run Code Online (Sandbox Code Playgroud)
但是,由于该成员是私人成员并且无法从课堂外获得,因此这不太有用.值得庆幸的是,假设的类Object为其封装的成员提供了getter和setter.但是我们现在需要将序列化拆分为单独的保存和加载功能,幸运的是,boost也允许这样做.不幸的是,似乎只有在用户使用侵入式方法时才能进行此拆分.为了告诉提升分裂功能,官方文档引用了这个宏.
BOOST_SERIALIZATION_SPLIT_MEMBER()
Run Code Online (Sandbox Code Playgroud)
这意味着:
template<class Archive>
void serialize(Archive &ar, const unsigned int file_version)
{
boost::serialization::split_member(ar, *this, file_version);
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,这需要放在里面,这正是我想避免在首位的类.
围绕boost邮件列表,我遇到了这个解决方案:
template <class Archive>
void serialize(Archive & ar, Object& o, const unsigned int version)
{
boost::serialization::split_free(ar, o, version);
}
Run Code Online (Sandbox Code Playgroud)
现在一切似乎都在最后,但我的编译器决定不同并打印此错误消息:
error: no matching function for call to 'load(boost::archive::text_iarchive&, Object&, const boost::serialization::version_type&)'
error: no matching function for call to 'save(boost::archive::text_oarchive&, const Object&, const boost::serialization::version_type&)'
split_free.hpp:45:9: note: cannot convert 't' (type 'const Object') to type 'const boost_132::detail::shared_count&'
Run Code Online (Sandbox Code Playgroud)
我到底错在了什么?
moc*_*ace 15
当你使用时,boost::serialization::split_free()
你必须提供splitted load()
和save()
方法,这就是编译器所抱怨的.
使用您的示例并假设这Member
是您无法修改的外部对象,请按如下方式实现序列化:
// outside of any namespace
BOOST_SERIALIZATION_SPLIT_FREE(Member)
namespace boost { namespace serialization {
template<class Archive>
void save(Archive& ar, const Member& m, unsigned int) {
...
}
template<class Archive>
void load(Archive& ar, Member& m, unsigned int) {
...
}
}} // namespace boost::serialization
class Object {
private:
Member member;
public:
template<class Archive>
void serialize(Archive& ar, const unsigned int) {
ar & member;
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3591 次 |
最近记录: |