1

如果我有类似以下的情况,其中类 B 派生自不同命名空间中的类 A,则序列化输出无法验证基类的标记名称,从而产生“无效的 XML 标记名称”。

我该如何处理这种情况?

#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/base_object.hpp>

namespace N {

struct A
{
    friend class boost::serialization::access;
    int m_a;

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

}



struct B : N::A
{
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(N::A);
    }
};



int main ()
{
    B b;
    boost::archive::xml_oarchive ar(std::cout);
    ar << BOOST_SERIALIZATION_NVP(b);
}

输出是:

 <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="9">
<b class_id="0" tracking_level="0" version="0"terminate called after throwing an instance of 'boost::archive::xml_archive_exception'
  what():  Invalid XML tag name
The program has unexpectedly finished.
4

1 回答 1

3

由于您使用不同的命名空间,BOOST_SERIALIZATION_BASE_OBJECT_NVP并且BOOST_SERIALIZATION_NVP不工作。相反,您需要boost::serialization::make_nvp在这两种情况下都使用。

于 2013-08-23T13:10:59.680 回答