从boost序列化归档构造对象

时间:2012-03-06 18:26:31

标签: c++ boost boost-serialization

是否可以直接从存档构建对象?

像这样......

// Non-working pseudo code
struct Foo {
    BOOST_SERIALIZATION_SPLIT_MEMBER();
    std::vector<int> data;

    Foo() {
        // populate "data" by doing calculation
        data.push_back(1); data.push_back(2);
    }

    template<class Archive>
    Foo( Archive & ar ) {
        // populate "data" by rading the archive
    }

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const {
        // Normal serialization of data
        ar << data;
    }
};

int main(int argc, const char *argv[])
{
    // deserialize
    boost::archive::text_iarchive oar(std::cin);
    Foo foo(oar);

    return 0;
}

2 个答案:

答案 0 :(得分:1)

您可以使用反序列化构造函数

With Worksheets("Analysis Worksheet")

答案 1 :(得分:0)

正如我在评论中所说的那样。 是的,从存档构建是没有问题的。 (另一种选择是具有static load功能,但可能会有性能损失。)

我用你的方法看到的唯一潜在问题是你的构造函数几乎可以将任何东西作为参数,这可能会产生问题。 这可能会干扰复制构造函数和依赖于隐式转换的其他单个参数构造函数。

因此,必须限制仅使用档案。

有不同的方法可以执行此操作,但基于此对话http://marc.info/?l=boost&m=121131260728308&w=2,以及archives 的继承树已记录{{3}我认为这是最好的解决方案是检查参数是否来自basic_iarchive

#include<type_traits>
struct Foo {
    ...
    std::vector<int> data;    
    Foo() {
        // populate "data" by doing calculation
        data.push_back(1); data.push_back(2);
    }

    template<class IArchive, 
        typename = std::enable_if_t<std::is_base_of<boost::archive::detail::basic_iarchive, IArchive>::value>>
    Foo( IArchive & ar ) {
        ar >> data;
        // populate "data" by reading the archive
    }
    ...    
};

int main(int argc, const char *argv[])
{
    // deserialize
    boost::archive::text_iarchive iar(std::cin); 
    Foo foo(iar); // will also work with other archives
}

至于当您的数据不是默认建设性时会发生什么,请参阅上面的讨论。