find out the class type inside the class and its children

后端 未结 1 711
一向
一向 2021-01-28 16:23

Lets say I have the class

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

  inline Ptr
          


        
相关标签:
1条回答
  • 2021-01-28 17:01

    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.

    0 讨论(0)
提交回复
热议问题