find out the class type inside the class and its children

拥有回忆 提交于 2019-12-20 06:00:42

问题


Lets say I have the class

template<typename PointT>
class Parent {
  public:
  typedef boost::shared_ptr<Parent<PointT> > Ptr;

  inline Ptr
  makeShared ()
  {
    return Ptr (new Parent<PointT> (*this));
  }
};

template<typename PointT>
class Child : public Parent {
  public:
    typedef boost::shared_ptr<Child<PointT> > Ptr;
};

Now what I'd like to rewrite the definition of Ptr and makeShared() to be generic, so that calling makeShared() from child class(es) instances would yield a pointer to the child class not the parent

To make it more clear calling makeShared() on any class inheriting Parent would give a pointer to an instance of that inheriting class. and calling make shared() on the parent class would give a pointer to an instance of Parent class Any ideas?


回答1:


CRTP will work here:

template<typename Child>
class Parent {
  public:
  typedef boost::shared_ptr<Child> Ptr;

  inline Ptr
  makeShared ()
  {
    return Ptr (new Child(*static_cast<Child *>(this)));
  }
};

template<typename PointT>
class Child : public Parent<Child> {
};

Note that makeShared is a fairly confusing name as it could be confused with shared_from_this (in C++11 and Boost). A more typical name for your method is clone.



来源:https://stackoverflow.com/questions/12077471/find-out-the-class-type-inside-the-class-and-its-children

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