c++ - 最终子类错误的基类的Boost序列化

标签 c++ boost c++11 boost-serialization

我正在尝试使用 boost::serialization 序列化一个类,但当派生类声明为 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

如果final省略说明符就没有错误。这个错误的原因是什么以及如何避免它?

最佳答案

原因是 is_virtual_base_of(Boost 的实现细节)尝试从其参数中派生来确定(通过比较大小)一个类是否是另一个类的虚拟基类。

在编写本文时,还没有 final 类,因此尚未考虑这种情况。您可能想在 Boost 邮件列表上询问是否有人可以 boost/修复它,这可能是可能的,也可能是不可能的。传统上,Boost 会尽力检测类型特征,但能做的事情是有限的。大多数编译器都有内置方法来确定某些类型属性,因为仅使用 C++ 代码无法检测它们。

关于c++ - 最终子类错误的基类的Boost序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18982064/

相关文章:

android - 使用 QtCreator 使用 BOOST_ALL_NO_LIB 构建 android 时未定义对 boost::system::system_category 的引用

c++ - boost program_options 自定义验证

c++ - 使用 boost - 将它放在源代码管理中还是让任何开发人员自己安装?

c++ - void* 和 char* 的区别

c++ - std::to_string 在 header 字符串中不可用

c++ - 我可以通过重新播种结合 random_device 和 mt19937 生成加密安全随机数据吗?

c++ - std::getline() 返回

c++ - 让子窗口继承父背景颜色?

C++: "Class namespaces"?

c++ - Windows I/O 驱动程序中的主动等待