Storing a type in C++

后端 未结 8 1402
春和景丽
春和景丽 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 18:09

    Types are not objects in C++ (where they are in Ruby, for instance), so you cannot store instances of a type. Actually, types never appear in the executing code (RTTI is just extra storage).

    Based on your example, it looks like you're looking for typedefs.

    typedef int Number;
    Number one = 1;
    Number* best = (Number*) one;
    

    Note that a typedef isn't storing the type; it is aliasing the type.

提交回复
热议问题