Surcle
Surcle

Reputation: 582

Boost Serialize data in a custom way

Suppose that I've a list of objects stored somewhere in a map . My goal is to serialize all shared pointers through a key like this:

namespace boost { namespace serialization {

template<class Archive, class T>
inline void serialize(Archive& ar, boost::shared_ptr<T>& b, const unsigned int file_version)
{
    std::string key_of_b = // get a key of object b;
    ar << key_of_b;
}

} }

Then, during the serialization through the key serialized, get back the object in the map. Is it possible to serialize-deserialize the object by using only the boost::shared_ptr? Like:

int main() {

        std::stringstream ss;

        // serialize
        boost::shared_ptr<int> p{new int{1123}};
        boost::archive::text_oarchive oa(ss);
        oa << p1;

        // deserialize
        boost::archive::text_iarchive ia(ss);
        boost::shared_ptr<int> p_i{new int{1123}};
        ia >> p_i;

        return 0;
    }

I know that the code cannot work in this way. I thought to handle the serialization/deserialiazion in the serialize method:

template<class Archive, class T>
    inline void serialize(Archive& ar, boost::shared_ptr<T>& b, const unsigned int file_version)
    {
        if (boost::archive::text_oarchive::is_saving::value) {
          std::string key_of_b = // get a key of object b;
          ar << key_of_b;
        } else {
          std::string key;
          ar >> key;
          // get the T
        }
    }

Is that correct or there is another better way?

Upvotes: 0

Views: 614

Answers (1)

sehe
sehe

Reputation: 392999

Since you're specifically talking about certain T, don't provide an overly generic serialize template inside the boost namespaces.

Instead, leverage ADL and put it with your custom type:

namespace MyLib {
    struct MyType { /*....*/ };

    template<class Archive>
    void save(Archive& ar, boost::shared_ptr<MyType> const& p, unsigned)
    {
        ...
    }
    template<class Archive>
    void load(Archive& ar, boost::shared_ptr<MyType>& p, unsigned)
    {
        ...
    }

    template<class Archive> inline void serialize(Archive& ar, boost::shared_ptr<MyType>& p, unsigned file_version) {
        split_free(ar, p, file_version); 
    }

} // namespace MyLib

About split_free see documentation

Upvotes: 1

Related Questions