Search code examples
c++serializationboostboost-serialization

How can I remove this duplicate code when using Boost serialization?


In my application I have a number of classes that I want to be able to serialize. So each class whose instances need to be serializeable has the following:

    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
       // ar & (all data members) 
    }

To serialize the object I then need to use this code from outside the class:

    ObjectToSerialize obj;
    stringstream ss;
    boost::archive::text_oarchive oa(ss);
    oa << obj;

This second block of code is annoying me because I have to use it everytime I want to serialize an object. Is there any way I can move this code to one location and call it when I need to serialize an object?

I could have an object with this method:

    string serializeObject(Serializable obj)

But the problem with this is that there is no way to determine which objects are 'serializable' as there is no supertype that a class must implement when adding boost seriization functionality.

So how can I put this code in one place and only allow objects that are serializable to be passed to the method?


Solution

  • Make a template function that takes a object that has a serialize function.

    template <typename T> std::string serializeObject(T obj) {
        stringstream ss;
        boost::archive::text_oarchive oa(ss);
        oa << obj;
        //...
    }
    
    
    std:String str = serializeObject(ObjectToSerialize);