Creating a new object from dynamic type info

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

    I used macros in my project to synthesize such methods. I'm just researching this approach now, so I may be wrong, but here's an answer to your question in my code of IAllocable.hh. Note that I use GCC 4.8, but I hope 4.7 suits.

    #define SYNTHESIZE_I_ALLOCABLE \
        public: \
        auto alloc() -> __typeof__(this) { return new (__typeof__(*this))(); } \
        IAllocable * __IAllocable_alloc() { return new (__typeof__(*this))(); } \
        private:
    
    
    class IAllocable {
    public:
        IAllocable * alloc() {
            return __IAllocable_alloc();
        }
    protected:
        virtual IAllocable * __IAllocable_alloc() = 0;
    };
    

    Usage:

    class Usage : public virtual IAllocable {
    
        SYNTHESIZE_I_ALLOCABLE
    
    public:
        void print() {
            printf("Hello, world!\n");
        }
    };
    
    int main() {
        {
            Usage *a = new Usage;
            Usage *b = a->alloc();
    
            b->print();
    
            delete a;
            delete b;
        }
    
        {
            IAllocable *a = new Usage;
            Usage *b = dynamic_cast(a->alloc());
    
            b->print();
    
            delete a;
            delete b;
        }
     }
    

    Hope it helps.

提交回复
热议问题