Creating a new object from dynamic type info

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

    You can use e.g. typeid to query an object's dynamic type, but I don't know of a way to directly instantiate a new object from the type information.

    However, apart from the clone approach mentioned above, you could use a factory:

    #include <typeinfo>
    #include <iostream>
    
    class Base
    {
    public:
        virtual void foo() const
        {
            std::cout << "Base object instantiated." << std::endl;
        }
    };
    
    
    class Derived : public Base
    {
    public:
        virtual void foo() const
        {
            std::cout << "Derived object instantiated." << std::endl;
        }
    };
    
    
    class Factory
    {
    public:
        static Base* createFrom( const Base* x )
        {
            if ( typeid(*x) == typeid(Base) )
            {
                return new Base;
            }
            else if ( typeid(*x) == typeid(Derived) )
            {
                return new Derived;
            }
            else
            {
                return 0;
            }
        }
    };
    
    
    int main( int argc, char* argv[] )
    {
        Base* X = new Derived;
        if ( X != 0 )
        {
            std::cout << "X says: " << std::endl;
            X->foo();
        }
    
        Base* Y = Factory::createFrom( X );
        if ( Y != 0 )
        {
            std::cout << "Y says: " << std::endl;
            Y->foo();
        }
    
        return 0;
    }
    

    P.S.: The essential part of this code example is of course the Factory::createFrom method. (It's probably not the most beautiful C++ code, since my C++ has gone a little rusty. The factory method probably shouldn't be static, on second thought.)

    0 讨论(0)
  • 2020-12-05 05:58
    class Base
    {
    public:
     virtual ~Base() { }
    };
    
    class Foo : public Base
    {
    
    };
    
    class Bar : public Base
    {
    
    };
    
    template<typename T1, typename T2>
    T1* fun(T1* obj)
    {
     T2* temp = new T2();
     return temp;
    }
    
    int main()
    {
      Base* b = new Foo();
      fun<Base,Foo>(b);
    }
    
    0 讨论(0)
提交回复
热议问题