问题
In the curiously recurring template pattern, we write
template <class Derived>
class Base {
};
class Derived : public Base<Derived> {
};
What would be a good way to make the code robust another copy-paste omissions, so that the following snippet throws a compile-time error:
class AnotherDerived : public Base<Derived> {
};
I'm using Visual C++ 2013.
回答1:
Make Base
's destructor private, and then make Derived
a friend of Base<Derived>
:
template <class Derived>
class Base {
private: ~Base() = default;
friend Derived;
};
class Derived : public Base<Derived> {
};
This does not actually make doing
class AnotherDerived : public Base<Derived> {
};
illegal, but any attempt to actually construct an AnotherDerived
will fail.
回答2:
You can static_assert
that the argument derives from Base<Argument>
, but that's as far as you can go.
来源:https://stackoverflow.com/questions/28548958/how-to-secure-crtp-against-providing-wrong-superclass