Search code examples
c++boost-serialization

C++ Boost.Serialization - Non intrusive serialization of user-defined members?


I have a class structure like

class MemberClass;

class ContainerClass {
  MemberClass special_member;
  int other_members;
};

Following the example in http://www.boost.org/doc/libs/1_66_0/libs/serialization/doc/ i want to write an non-intrusive serialization:

template<class Archive>
void serialize(Archive & ar, ContainerClass & c, const unsigned int version)
{
    ar & c.other_members; // easy - built-in type
    serialize(ar, c.special_member, version);  //???
}

Assuming there's is also a non-intrusive

void serialize(Archive & ar, MemberClass & m, const unsigned int version);

this compiles and works but i feel this is not the way to do it because it reuses the version number of the container class for the member class?

So how to handle that? Must the Container class manage version of its members individually?


Solution

  • The answer is that writing

    template<class Archive>
    void serialize(Archive & ar, ContainerClass & c, const unsigned int version)
    {
        ar & c.other_members;
        ar & c.special_member;
    }
    

    Will work just fine, even if we only have the non-intrusive version of

    void serialize(Archive & ar, MemberClass & m, const unsigned int version);
    

    I wasn't aware of that.

    You should never explicitly call the external serialize function.