Boost的序列化如何确定多态对象的运行时类型

时间:2019-07-14 05:43:52

标签: c++ serialization boost dynamictype

我一直在阅读this的示例,该示例演示了Boost如何简单地通过强制使用这些对象的类将多态对象称为Archive::template register_type<Dynamic_type>()来序列化多态对象。

template<class Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        // in this program, these classes are never serialized directly but rather
        // through a pointer to the base class bus_stop. So we need a way to be
        // sure that the archive contains information about these derived classes.
        //ar.template register_type<bus_stop_corner>();
        ar.register_type(static_cast<bus_stop_corner *>(NULL));
        //ar.template register_type<bus_stop_destination>();
        ar.register_type(static_cast<bus_stop_destination *>(NULL));
        // serialization of stl collections is already defined
        // in the header
        ar & stops;
    }

这使我在一天的休息中花了四个小时思考如何使用像C ++这样没有反射的语言来完成此工作,最后我什么都没想到。

从逻辑上讲,我假设调用register_type<T>时库正在集合中存储一些类型信息。然后,它尝试将存储的类型信息与从要序列化的对象的运行时类型生成的类型信息进行比较。如果类型信息匹配,则将该对象向下转换为相应的类型。但是根本没有办法将对象转换为仅在C ++运行时才知道的类型。那么,库如何将对象转换为动态类型,以便可以正确地对对象进行序列化(反序列化)?

0 个答案:

没有答案