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

后端 未结 6 2079
迷失自我
迷失自我 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:30

    You could use CRTP to add an additional layer between your derived class and base that implements your cloning method.

    struct Base {
        virtual ~Base() = default;
        virtual Base* clone() = 0;
    };
    
    template 
    struct Base_with_clone : Base {
        Base* clone() {
            return new T(*this);
        }
    };
    
    struct Derived : Base_with_clone {};
    

提交回复
热议问题