2

我在这里做错了吗?如果我删除首先序列化基础的注释,它会起作用,否则我会收到错误:

terminate called after throwing an instance of 'boost::archive::archive_exception'
    what():  input stream error
Aborted

这是代码:

struct A
{
    virtual ~A() {};

    int i1 = 10;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & make_nvp("int", i1);
    }
};
struct B : A
{
    virtual ~B() {};

    float f1 = 5.0F

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<A>(*this);
        ar & make_nvp("float", f1);
    }
};
struct C : A
{
    virtual ~C() {};

    long l1 = 24;

    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar & boost::serialization::base_object<A>(*this);
        ar & make_nvp("long", l1);
    }
};

//Why do these need to be wrappers??
namespace boost
{
namespace serialization
{
template<> struct is_wrapper<A*> : mpl::true_ {};
template<> struct is_wrapper<A> : mpl::true_ {};
template<> struct is_wrapper<const A> : mpl::true_ {};
}
}

BOOST_SERIALIZATION_ASSUME_ABSTRACT(A);
BOOST_CLASS_EXPORT(B)
BOOST_CLASS_EXPORT(C)

int main(int argc, char** argv)
{
    //A* a = new A();
    A* b = new B();
    A* c = new C();
    //A* a1 = nullptr;
    A* a2 = nullptr;
    A* a3 = nullptr;

    ostringstream ostream;
    xml_oarchive oarchive(ostream);

    oarchive << /*BOOST_SERIALIZATION_NVP(a) <<*/ BOOST_SERIALIZATION_NVP(b) << BOOST_SERIALIZATION_NVP(c);

    istringstream istream(ostream.str());
    xml_iarchive iarchive(istream);

    iarchive >> /*BOOST_SERIALIZATION_NVP(a1) >>*/ BOOST_SERIALIZATION_NVP(a2) >> BOOST_SERIALIZATION_NVP(a3);

    //delete a;
    delete b;
    delete c;
    //delete a1;
    delete a2;
    delete a3;
}

相同的代码在两种情况下都适用于文本和二进制存档......

编辑:这是使用 Boost 1.53 和 GCC 4.8 w/std=c++11

4

0 回答 0