How can Boost's Serialization determine the run-time type of a polymorphic object

153 Views Asked by At

I've been reading this example which demonstrated how Boost can serialize polymorphic objects simply by mandating that classes using these objects polymorphically call 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;
    }

This made me go on a four hour brain storm on my day off on how this can be done in a language like C++ that has no reflection, and in the end I came up with nothing.

Logically, I assume the library is storing some type information in a collection when register_type<T> is called. Then, it attempts to compare the type information stored with the type information generated from the run-time type of the object being serialized. If the type information matches, then that object is downcasted to the corresponding type. But there simply is no way to cast an object to a type that is only known during run-time in C++. So how can the library downcast the object to its dynamic type so that the object can be properly (de)serialized?

0

There are 0 best solutions below