Creating a new object from dynamic type info

前端 未结 8 1002
南旧
南旧 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:32

    When there are extremely many classes deriving from the same base class then this code will save you from having to include clone methods every class. It's a more convenient way of cloning that involves templates and an intermediate subclass. It's doable if the hierarchy is shallow enough.

    struct PureBase {
        virtual Base* Clone() {
            return nullptr;
        };
    };
    
    template
    struct Base : PureBase {
        virtual Base* Clone() {
            return new T();
        }
    };
    
    struct Derived : Base {};
    
    int main() {
        PureBase* a = new Derived();
        PureBase* b = a->Clone(); // typeid(*b) == typeid(Derived)
    }
    

提交回复
热议问题