Is it possible to clone a polymorphic object without manually adding overridden clone method into each derived class in C++?

后端 未结 6 2112
迷失自我
迷失自我 2020-12-30 01:21

The typical pattern when you want to copy a polymorphic class is adding a virtual clone method and implement it in each derived class like this:

Base* Derive         


        
6条回答
  •  醉酒成梦
    2020-12-30 01:52

    You can at minimum avoid writing the class name by getting it from the type of the class itself with:

    struct A: public Base
    {
        Base* Clone() { return new std::remove_reference_t(*this); }
    };
    

    Using CRTP will not help avoid duplicating the class name again, as you than have to write the class name inside the template parms for the CRTP base.

提交回复
热议问题