How to make restrictions about the derived class?

Viewed 78

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>
{
    //...
};

void f()
{
    // undefined behavior: B object was static_cast to A
    B{}.foo();
}

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

1 Answers

You can make Base<D> constructor (or destructor) private and friend D.

You'll need to add

A()=default;
B()=default;

publicly, but when you do, B can't be created. Which is good.

Related