首页 > 解决方案 > Boost的Serialization如何判断多态对象的运行时类型

问题描述

我一直在阅读这个例子,它演示了 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++ 运行时才知道的类型。那么库如何将对象向下转换为其动态类型,以便可以正确(反)序列化对象?

标签: c++serializationboostdynamictype

解决方案


推荐阅读