有没有办法只允许在 C++ 中继承 final 类

Is there a way to allow inheritance only for final classes in C++

我有一个基础 class,我想从 继承 由 classes 标记为最终(或 classes它们本身不是从继承而来的)。

基本思想是我想在编译时禁止其他超级class继承这个class。

例如:

class O { /* Some compile time check here */ };
class A final : O {}; // OK
class B : O {}; // Not OK

我知道这可以在 class A 中通过使用类似的东西来完成:

if ( std::is_base_of<O,A>::value ) static_assert( std::is_final<A>::value );

但这需要写在每个 class 中。我希望这张支票在 class O 中(但我不知道这是否可能)。

谢谢

您可以同时使用 CRTP 和 std::is_final。

#include <type_traits>

template <typename CRTP>
class Base {
public:
    ~Base() {
        static_assert( std::is_final<CRTP>::value );
    }
};

// This will trip a compile time static_assert when the class is instantiated.
class Derived : Base<Derived> { 
};

class DerivedAndFinal final : Base<DerivedAndFinal> {
};

int main() {
    Derived d;
    (void)d;
    DerivedAndFinal daf;
    (void)daf;
}