Creating a new object from dynamic type info

前端 未结 8 995
南旧
南旧 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 
    #include 
    
    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.)

提交回复
热议问题