Search code examples
c++compile-time

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


I have a base class that I want to be inherited from only by classes marked as final (or classes that are not themselves inherited from).

The underlying idea is that I want to forbid inheritance from this class by other superclasses, at compile time.

For example:

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

I know this could be done in class A by using something like:

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

But this would need to be written in every single class. I'd like this check to be in class O (but I don't know if that's even possible).

Thank you


Solution

  • You can use CRTP and std::is_final together.

    #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;
    }