C++ elegantly clone derived class by calling base class

后端 未结 3 662
滥情空心
滥情空心 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 05:03

    You can rely on the CRTP idiom.
    It follows a minimal, working example:

    struct B {
        ~virtual ~B() { }
        virtual B* clone() = 0;
    };
    
    template
    struct D: public B {
        B* clone() {
            return new C{*static_cast(this)};
        }
    };
    
    struct S: public D { };
    
    int main() {
        B *b1 = new S;
        B *b2 = b1->clone();
        delete b1;
        delete b2;
    }
    

提交回复
热议问题