如何保护 CRTP 不提供错误的超类?

How to secure CRTP against providing wrong superclass?

curiously recurring template pattern中,我们写

template <class Derived>
class Base {
};

class Derived : public Base<Derived> {
};

什么是使代码健壮的好方法另一个复制粘贴遗漏,以便以下代码段引发编译时错误:

class AnotherDerived : public Base<Derived> {
};

我正在使用 Visual C++ 2013。

您可以 static_assert 论点源自 Base<Argument>,但您只能做到这一点。

Base 的析构函数设为私有,然后将 Derived 设为 Base<Derived> 的好友:

template <class Derived>
class Base {
    private: ~Base() = default;
    friend Derived;
};

class Derived : public Base<Derived> {
};

这并不能真正做到

class AnotherDerived : public Base<Derived> {
};

非法,但任何实际构建 AnotherDerived 的尝试都会失败。