如何通过指向基类的序列化派生类? Derived :: serialize未调用

时间:2014-11-17 02:57:24

标签: c++ serialization boost polymorphism

我试图通过使用指向基类的指针进行boost序列化来使派生类可序列化。

调用Base :: serialization。 Derived :: serialization未调用。

我做错了什么?

#include <sstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/assume_abstract.hpp>

struct Base
{
    int x;
    Base() { x = 0; }
    virtual ~Base() {}

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

BOOST_SERIALIZATION_ASSUME_ABSTRACT(Base)

struct Derived : Base
{
    int y;
    Derived() { x = 1; y = 2; }
    virtual ~Derived() {}

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<Base>(*this);
        ar & y;
    }
};

int main()
{
    Derived derived;
    Base *basePtr = &derived;

    std::string s;
    std::stringstream ss(s);
    boost::archive::binary_oarchive oa(ss);

    oa << *basePtr;
}

1 个答案:

答案 0 :(得分:1)

首先,你没有通过指针序列化,修复它:

oa << basePtr;

其次,您需要注册派生类型:

oa.register_type<Derived>();

或者,在序列化函数中:

ar.template register_type<Derived>();

您可能还想查看注册序列化的类信息:http://www.boost.org/doc/libs/1_57_0/libs/serialization/doc/special.html#export


更新到评论/已编辑的问题:

您的问题代码序列化Base*并反序列化Derived。这些类型是无关的,这可能永远不会奏效。他们需要完全相同。

此外,注册读取输入存档的派生类型。

<强> Live On Coliru

#include <sstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/assume_abstract.hpp>

struct Derived;

struct Base
{
    int x;
    Base() { x = 0; }
    virtual ~Base() {}

    template<class Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar.template register_type<Derived>();
        ar & x;
    }
};

BOOST_SERIALIZATION_ASSUME_ABSTRACT(Base)

struct Derived : Base
{
    int y;
    Derived() { x = 1; y = 2; }
    virtual ~Derived() {}

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<Base>(*this);
        ar & y;
    }
};

int main()
{
    std::stringstream ss;

    {
        Derived derived;
        Base *basePtr = &derived;

        boost::archive::binary_oarchive oa(ss);
        oa.register_type<Derived>();

        oa << basePtr;
        ss.flush();
    }

    {
        boost::archive::binary_iarchive ia(ss);
        ia.register_type<Derived>();

        Base *basePtr = nullptr;

        ia >> basePtr;
        std::cout << "basePtr->x = " << basePtr->x << "\n";
        if (Derived* derivedPtr = dynamic_cast<Derived*>(basePtr))
            std::cout << "derivedPtr->y = " << derivedPtr->y << "\n";
    }
}