I have the following base template class.
template<typename T>
class Base {
public:
void do_something() {
}
};
It is intended to be used as a curiously recurring template pattern. It should be inherited like class B : public Base<B>
. It must not be inherited like class B : public Base<SomeoneElse>
. I want to statically enforce this requirement. If someone uses this wrong, I expect an error in the compiling phase.
What I'm doing is putting a static_cast<T const&>(*this)
in do_something()
. This way the class inheriting the template is or inherits from the class provided as the template parameter. Sorry for the confusing expression. In plain English, it requires B
is or inherits from SomeoneElse
in class B : public Base<SomeoneElse>
.
I don't know if it's the optimal way to achieve this. Looks gross to me.
However I want to do more. I want to ensure B
is SomeoneElse
itself. How can I do that?
Make the constructor (or destructor) of Base
private, and then make T
a friend
. This way the only thing that can construct/destruct a Base<T>
is a T
.
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