Question

I'm trying to serialize a class using boost::serialization, but it fails when a derived class is declared as final.

#include <fstream>

#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/archive/binary_oarchive.hpp>

class Base {
public:
    virtual ~Base() = default;
    virtual void Foo() = 0;

private:
    friend class boost::serialization::access;
    template <typename Archive>
    void serialize(Archive& archive, const unsigned int version) {}
};

class Derived final: public Base {
public:
    void Foo() override {}

private:
    friend class boost::serialization::access;
    template <typename Archive>
    void serialize(Archive& archive, const unsigned int version) {
        archive & boost::serialization::base_object<Base>(*this);
    }
};

int main() {
    Derived foo;

    std::ofstream output("output");
    boost::archive::binary_oarchive archive(output);
    archive << foo;
}

error: cannot derive from ‘final’ base ‘Derived’ in derived type ‘boost::detail::is_virtual_base_of_impl<Base, Derived, mpl_::bool_<true> >::boost_type_traits_internal_struct_X’ struct boost_type_traits_internal_struct_X : public Derived, virtual Base

If the final specificator is ommitted there is no error. What's the reason for this error an how it could be avoided?

Was it helpful?

Solution

The reason is that is_virtual_base_of, an implementation detail of Boost, tries to derive from its parameters to detemine (by comparing sizes) whether or not a class is the virtual base of another class.

At the time it was written, there were no final classes and therefore this case has not been considered. You might want to ask on the Boost mailing list if someone could enhance/fix it, which might or might not be possible. Boost traditionally tried its best to detect type traits, but there are limits to what can be done. Most compilers have built-in methods to determine certain type properties because there is no way to detect them with only C++ code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top