Creating a new object from dynamic type info

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

    class Base
    {
    public:
     virtual ~Base() { }
    };
    
    class Foo : public Base
    {
    
    };
    
    class Bar : public Base
    {
    
    };
    
    template
    T1* fun(T1* obj)
    {
     T2* temp = new T2();
     return temp;
    }
    
    int main()
    {
      Base* b = new Foo();
      fun(b);
    }
    

提交回复
热议问题