Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make restrictions about the derived class?

Tags:

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

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?

like image 841
lvella Avatar asked Dec 20 '25 11:12

lvella


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.

like image 164
Yakk - Adam Nevraumont Avatar answered Dec 22 '25 23:12

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!