AK_ AK_ - 3 months ago 12
C++ Question

c++ boost::serialization setting a fixed class_id for a class

I'mm using boost to serialize and deserialize some classes

Like so:

boost::archive::xml_oarchive xmlArchive(oStringStream);

xmlArchive.register_type(static_cast<BaseMessage *>(NULL));
xmlArchive.register_type(static_cast<IncomingTradeMessage *>(NULL));
xmlArchive.register_type(static_cast<InternalRequestInfo *>(NULL));
xmlArchive.register_type(static_cast<InternalTradeTransInfo *>(NULL));

const BaseMessage* myMessage =message;

xmlArchive << make_nvp("Message", myMessage);


now my clasess get a class_id according to the order used, i dont want that, i want to control the Class_id's

so i can do something like

BOOST_SET_CLASS_ID(1234, BaseMessage);


and everywhere in my project BaseMessage would have class_id of 1234.

How can i do such a thing

Answer

Can't you use BOOST_CLASS_EXPORT_GUID or similar instead? I.e.

BOOST_CLASS_EXPORT_GUID(IncomingTradeMessage, "IncomingTradeMessage")
...

It will use some more bandwidth since strings are transmitted rather than integers, but it will solve your problem.

Refer to this and this for more info.

EDIT:

This compile just fine:

#include <fstream>
#include <boost/serialization/export.hpp>
#include <boost/archive/text_oarchive.hpp>

class Foo {
    friend class boost::serialization::access;

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

    int dummy1;

public:
    virtual ~Foo() {}
};

class Bar : public Foo {
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        // serialize base class information
        ar & boost::serialization::base_object<Foo>(*this);
        ar & dummy2;
    }

    int dummy2;
};

BOOST_CLASS_EXPORT_GUID(Foo, "Foo")
BOOST_CLASS_EXPORT_GUID(Bar, "Bar")

int main(int argc, char *argv[]) {
    std::ofstream ofs("filename");
    boost::archive::text_oarchive oa(ofs);
    Foo *f = new Bar;
    oa << f;

    return 0;
}