问题 提升:在单独的加载/保存功能中非侵入式序列化类


我目前正在开发一个软件项目,该项目需要对象持久性作为其实现的一部分。升级序列化库乍一看似乎完全适合这项工作,但现在我已经尝试使用它,我开始质疑它的整体设计。

库希望用户为用户想要序列化的每个类定义序列化方法。

class Object
{
private:
    int member;
public:
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & member;
    }
};

如果有问题的类具有属于其他第三方库和API的成员对象,则会出现问题。即使我碰巧使用的那些都在zlib许可下可用,修改库头只是感觉不对。

但是开发人员已经想到了这一点,并提供了一个非侵入式版本,允许在不修改它们的情况下向类添加序列化。辉煌。

template<class Archive>
void serialize(Archive & ar, Object& o, const unsigned int version)
{
    ar & o.member;
}

但是,由于该成员是私人成员并且无法在课堂外进行考虑,因此这不太有效。值得庆幸的是,假设的类Object为其封装的成员提供了getter和setter。但是我们现在需要将序列化拆分为单独的保存和加载功能,幸好boost也允许这样做。不幸的是,似乎这种分裂只有在用户使用时才有可能 侵入 方法。为了告诉提升分裂功能,官方文档引用了这个宏。

BOOST_SERIALIZATION_SPLIT_MEMBER()

这意味着:

template<class Archive>                                          
void serialize(Archive &ar, const unsigned int file_version)
{                                                               
    boost::serialization::split_member(ar, *this, file_version); 
}

如您所见,这需要放置  这个类正是我想要首先避免的。

围绕boost邮件列表,我遇到了这个解决方案:

template <class Archive>
void serialize(Archive & ar, Object& o, const unsigned int version)
{
    boost::serialization::split_free(ar, o, version);
} 

现在一切似乎都在最后,但我的编译器决定不同并打印此错误消息:

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&'

我到底错在了什么?


1712
2018-01-03 00:23


起源

是否根据答案帮助将方法添加到boost :: serialization命名空间,或者仍然是非侵入式序列化的问题? - mockinterface


答案:


当你使用 boost::serialization::split_free() 你必须提供分裂 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;
    }
};

14
2018-01-13 09:18