Search code examples
c++boostboost-serializationboost-variant

boost Serialisation on a variant containing boost::blank


I have a boost::variant wherein one of the fields has the boost::blank field, using boost::serialise on the same throws an error saying error: no member named 'serialize' in 'boost::blank'.

Is there a way to avoid this by adding a separate function for boost::blank somewhere?


Solution

  • Yeah, just use non-member serialization, a.k.a. non-intrusive serialization:

    namespace boost { namespace serialization {
        template <typename Ar> void serialize(Ar&, boost::blank&, unsigned) {}
    } }
    

    You could also add the overload in namespace boost as ADL will find it there

    Live Demo

    Live On Coliru

    #include <boost/archive/text_oarchive.hpp>
    #include <boost/serialization/variant.hpp>
    #include <iostream>
    
    using V = boost::variant<boost::blank, int>;
    
    namespace boost { namespace serialization {
        template <typename Ar> void serialize(Ar&, boost::blank&, unsigned) {}
    } }
    
    int main() {
        V a{42}, b;
    
        boost::archive::text_oarchive oa(std::cout);
        oa << a << b;
    }
    

    Prints e.g.

    22 serialization::archive 17 1 0
    0 1 42
    1 0 0 0