问题
How to avoid
template <typename Derived>
struct base { int foo() { return static_cast<Derived*>(this)->bar(); } };
struct derived : base<derived> { int bar(); };
struct another_derived : base<derived> { int bar(); }; // error: wrong base
without additional code in derived classes?
This has been asked twice before (though without the extra condition of avoiding additional code in derived classes), with the recommended answer
template <typename Derived>
struct base {
int foo() { return static_cast<Derived*>(this)->bar(); }
private:
~base() {}
friend Derived;
};
However, this not only secures against above error, but also makes all private members of Base
accessible from Derived
. Is there an alternative, which avoids that? Or can it be conclusively shown that this is impossible?
edit
I actually have a more complex problem, where in addition to usual usage (as above) there is also
template<typename Derived>
struct intermediate : base<Derived>
{
int bar() { return static_cast<Derived*>(this)->ark(); }
};
when the private destructor trick fails (since intermediate
is not befriended by base
).
来源:https://stackoverflow.com/questions/33807223/securing-crtp-is-private-destructor-the-only-solution