'How does Boost Serialization make use of operator& to implement archiving / serialization?

How does Boost Serialization work?

In particular, Boost Serialization appears to make use of operator &.

How is it that defining a function like the following

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

in combination with friend class boost::serialization::access;

permits the following functions to be called?

std::ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);
oa << g;

Examples taken from the documentation.



Solution 1:[1]

You have boost::serialization::access acting as a place that's been friended by relevant types, which will expose serialise to the relevant parties.

Something like:

namespace boost::archive {

class access {
protected:
    template <typename T, typename Archive>
    void serialise(T & t, Archive & a, int version) {
        t.serialise(a, version);
    }
};

}

The archive types will inherit from boost::serialization::access, and also implement various operator &, including a catch-all template that calls serialise. E.g. for writing to a std::ostream

namespace boost::archive {

class oarchive : access {
public:
    void operator &(int i) { os << i; }
    /* other overloads for things that you can os << into */
    template <typename T>
    void operator &(T & t) { serialise(t, *this, version); }
private:
    std::ostream & os;
    int version = /* determine version somehow */;
}

}

Or for reading from a std::istream

namespace boost::archive {

class iarchive : access {
public:
    void operator &(int i) { is >> i; }
    /* other overloads for things that you can is >> out of */
    template <typename T>
    void operator &(T & t) { serialise(t, *this, version); }
private:
    std::istream & is;
    int version = /* determine version somehow */;
}

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caleth