如何避免
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
派生类中无需额外代码?
这已被问到twice https://stackoverflow.com/questions/28548958/how-to-secure-crtp-against-providing-wrong-superclass before https://stackoverflow.com/questions/4417782/how-to-avoid-errors-while-using-crtp(尽管没有避免在派生类中添加额外代码的额外条件),使用推荐的answer https://stackoverflow.com/a/7240019/1023390
template <typename Derived>
struct base {
int foo() { return static_cast<Derived*>(this)->bar(); }
private:
~base() {}
friend Derived;
};
然而,这不仅可以防止上述错误,而且还使得所有私有成员Base
可从Derived
。有没有替代方案可以避免这种情况?或者是否可以最终证明这是不可能的?
edit
我实际上有一个更复杂的问题,除了通常的用法(如上所述)之外,还有
template<typename Derived>
struct intermediate : base<Derived>
{
int bar() { return static_cast<Derived*>(this)->ark(); }
};
当私有析构函数技巧失败时(因为intermediate
不成为朋友base
).
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)