Securing CRTP: is private destructor the only solution?

丶灬走出姿态 提交于 2019-12-23 13:12:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!