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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With