带有谷物的可序列化对象

问题描述

  • 我有一个抽象类 BaseProduct,它由 ConcreteProduct 之类的类继承。
  • 我希望强制所有子类为 serealize 库实现 cereal 方法
  • 我不能将 serialize 声明为虚拟的,因为它应该是一个模板:
class BaseProduct {
public:
    BaseProduct();
    virtual ~BaseProduct();
    template<class Archive>
    virutal auto serialize(Archive & archive) -> void;  // This is wrong but kind of shows what I want
}

所以我希望孩子们被迫

class ConcreteProduct {
public:
    template<class Archive>
    serialize(Archive & archive) -> void override;  // Again wrong but lets say I don't want my code to compile if this method is not implemented for this class
}

是否有一个优雅的解决方案来确保我所有的 BaseProduct 都可以“serealizable”(cerealizable(?))?

PS:我只是关注cereal's simple tutorials

谢谢!

解决方法

使用 CRTP 可以做到这一点

template<typename Derived>
struct Base {
    template<typename Archive>
    void foo() {
        static_cast<Derived*>(this)->template foo<Archive>();
    }
};

struct Derived0 : Base<Derived0> {
    template<typename Archive>
    void foo() {
        
    }
};