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

后端 未结 6 2113
迷失自我
迷失自我 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 can use this generic CRTP code

    template 
    struct Clonable : Base {
        virtual Base* do_clone() {
            return new Derived(*static_cast(this));
        }
        Derived* clone() { // not virtual
            return static_cast(do_clone());
        }
    
        using Base::Base;
    };
    
    struct empty {};
    struct A : Clonable {};
    struct B : Clonable {};
    

    It can be generalised to smart pointers and multiple bases if desired.

提交回复
热议问题