Storing a type in C++

后端 未结 8 1400
春和景丽
春和景丽 2020-12-05 17:41

Is it possible to store a type name as a C++ variable? For example, like this:

type my_type = int; // or string, or Foo, or any other type
void* data = ...;
         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 17:49

    Not as written, but you could do something similar...

    class Type
    {
        public:
            virtual ~Type(){}
            virtual void* allocate()const=0;
            virtual void* cast(void* obj)const=0;
    };
    
    template class TypeImpl : public Type
    {
          public:
             virtual void* allocate()const{ return new T; }
             virtual void* cast(void* obj)const{ return static_cast(obj); }
    };
    
    // ...
    Type* type = new TypeImpl;
    void* myint = type->allocate();
    // ...
    

    This kind of thing can be extended depending on what features you need.

提交回复
热议问题