How can I use covariant return types with smart pointers?

后端 未结 7 1562
囚心锁ツ
囚心锁ツ 2020-11-27 17:42

I have code like this:

class RetInterface {...}

class Ret1: public RetInterface {...}

class AInterface
{
  public:
     virtual boost::shared_ptr

        
7条回答
  •  庸人自扰
    2020-11-27 18:20

    There is a neat solution posted in this blog post (from Raoul Borges)

    An excerpt of the bit prior to adding support for mulitple inheritance and abstract methods is:

    template 
    class clone_inherit : public Base
    {
    public:
       std::unique_ptr clone() const
       {
          return std::unique_ptr(static_cast(this->clone_impl()));
       }
    
    private:
       virtual clone_inherit * clone_impl() const override
       {
          return new Derived(*this);
       }
    };
    
    class concrete: public clone_inherit
    {
    };
    
    int main()
    {
       std::unique_ptr c = std::make_unique();
       std::unique_ptr cc = b->clone();
    
       cloneable * p = c.get();
       std::unique_ptr pp = p->clone();
    }
    

    I would encourage reading the full article. Its simply written and well explained.

提交回复
热议问题