Storing a type in C++

后端 未结 8 1439
春和景丽
春和景丽 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:06

    No you can't store the type directly as you want, but you can instead store the name of the type.

    const char* str = typeid(int).name();
    

    I guess whenever you planned to use that variable for comparison, you could instead at that time compare the str variable against the name() of the types.

    const char* myType = typeid(int).name();
    
    //....
    
    //Some time later:
    if(!strcmp(myType, typeid(int).name()))
    {
      //Do something
    }
    

    More info available here

提交回复
热议问题