find out the class type inside the class and its children

后端 未结 1 730
一向
一向 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
    class Parent {
      public:
      typedef boost::shared_ptr Ptr;
    
      inline Ptr
      makeShared ()
      {
        return Ptr (new Child(*static_cast(this)));
      }
    };
    
    template
    class Child : public Parent {
    };
    

    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)
提交回复
热议问题