How to make restrictions about the derived class?

  c++, c++20

Consider the curiously recurring template pattern, can you prevent the following unsafe code to compile?

template <class Derived>
class Base {
public:
    void foo()
    {
        // do something assuming "this" is of type Derived:
        static_cast<Derived>(*this).bar();
    }
};

// This is OK
class A: public Base<A>
{
public:
    void bar()
    {
        // ...
    }
};

// Crash and burn, should be prevented by the compiler
class B: public Base<A>
{
    //...
};

Is there a way to add some kind of restriction to class Base to prevent the definition of class B to be valid?

Source: Windows Questions C++

LEAVE A COMMENT