C++ elegantly clone derived class by calling base class

后端 未结 3 689
滥情空心
滥情空心 2021-01-15 04:12

I have a need to clone a derived class given only a reference or pointer to the base class. The following code does the job, but doesn\'t seem elegant, because I\'m putting

3条回答
  •  醉话见心
    2021-01-15 04:51

    To achieve clone that works as with covariant return type, there is a need for some more complicated CRTP:

    class Shape {
        // virtual
        virtual Shape* do_clone() const = 0;
    public:
        virtual ~Shape() {}
        // non-virtual
        Shape* clone() const {
            return do_clone();
        }
        // ...
    };
    
    template 
    class CloneCRTP : public Base {
        // virtual
        Shape* do_clone() const override {
            return new Derived(static_cast(*this));
        }
    public:
        // non-virtual
        Derived* clone() const {
            return static_cast(do_clone());
        }    
    };
    

    Usage:

    class Rectangle: public CloneCRTP { /*...*/ };    
    class Triangle: public CloneCRTP { /*...*/ };
    
    int main() {
        Rectangle* r1 = new Rectangle{};
    
        // getting the proper type from clone:
        Rectangle* rcopy = r1->clone();
    
        delete rcopy;
        delete r1;
    
        Triangle t1{};
    
        // getting the proper type from clone:
        Triangle* tcopy = t1.clone();
    
        delete tcopy;
    }
    

    Code: http://coliru.stacked-crooked.com/a/d8781deee5f7f6ea

提交回复
热议问题