Creating a new object from dynamic type info

前端 未结 8 986
南旧
南旧 2020-12-05 05:22

In C++, is there any way to query the type of an object and then use that information to dynamically create a new object of the same type?

For example, say I have a

8条回答
  •  自闭症患者
    2020-12-05 05:33

    The commonly used way to create copies of objects by base class is adding a clone method, which is essentially a polymorphic copy constructor. This virtual function normally needs to be defined in every derived class, but you can avoid some copy&paste by using the Curiously Recurring Template Pattern:

    // Base class has a pure virtual function for cloning
    class Shape {
    public:
        virtual ~Shape() {} // Polymorphic destructor to allow deletion via Shape*
        virtual Shape* clone() const = 0; // Polymorphic copy constructor
    };
    // This CRTP class implements clone() for Derived
    template  class Shape_CRTP: public Shape {
    public:
        Shape* clone() const {
            return new Derived(dynamic_cast(*this));
        }
    };
    // Every derived class inherits from Shape_CRTP instead of Shape
    // Note: clone() needs not to be defined in each
    class Square: public Shape_CRTP {};
    class Circle: public Shape_CRTP {};
    // Now you can clone shapes:
    int main() {
        Shape* s = new Square();
        Shape* s2 = s->clone();
        delete s2;
        delete s;
    }
    

    Notice that you can use the same CRTP class for any functionality that would be the same in every derived class but that requires knowledge of the derived type. There are many other uses for this besides clone(), e.g. double dispatch.

提交回复
热议问题