尝试使用boost::serialization
序列化派生类时,boost/archive/detail/oserializer.hpp
中的断言(Boost 1.53.0中的第436行)会被触发:
const basic_pointer_oserializer * bpos
= static_cast<const basic_pointer_oserializer *>(
boost::serialization::singleton<
archive_serializer_map<Archive>
>::get_const_instance().find(*true_type)
);
BOOST_ASSERT(NULL != bpos);
这是我的MWE:
#include <iostream>
#include <fstream>
#include <boost/archive/polymorphic_xml_oarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
class base
{
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::make_nvp("test", test);
}
int test;
public:
virtual void print() { std::cout << 1 << std::endl; }
};
class derived : public base
{
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::make_nvp("base", boost::serialization::base_object<base>(*this));
ar & boost::serialization::make_nvp("test2", test2);
}
int test2;
public:
void print() { std::cout << 2 << std::endl; }
};
int main (int argc, char const *argv[])
{
base *b = new derived();
std::ofstream stream("out.xml");
boost::archive::polymorphic_xml_oarchive ar(stream);
ar.register_type<derived>();
ar << boost::serialization::make_nvp("b", b);
return 0;
}
我也尝试使用BOOST_CLASS_EXPORT_GUID
代替register_type
,但这也行不通。知道我做错了吗?
答案 0 :(得分:2)
您可能并不想使用polymorphic_xml_archive (see docs)。
值得注意的是,多态存档与存档的界面有关,与您要序列化的实体无关(它们总是可以是多态的)。
如果您使用xml_archive
,问题就会消失。