Is it possible to print a variable's type in standard C++?

前端 未结 21 1664
南笙
南笙 2020-11-22 01:41

For example:

int a = 12;
cout << typeof(a) << endl;

Expected output:

int
21条回答
  •  灰色年华
    2020-11-22 02:11

    As mentioned, typeid().name() may return a mangled name. In GCC (and some other compilers) you can work around it with the following code:

    #include 
    #include 
    #include 
    #include 
    
    namespace some_namespace { namespace another_namespace {
    
      class my_class { };
    
    } }
    
    int main() {
      typedef some_namespace::another_namespace::my_class my_type;
      // mangled
      std::cout << typeid(my_type).name() << std::endl;
    
      // unmangled
      int status = 0;
      char* demangled = abi::__cxa_demangle(typeid(my_type).name(), 0, 0, &status);
    
      switch (status) {
        case -1: {
          // could not allocate memory
          std::cout << "Could not allocate memory" << std::endl;
          return -1;
        } break;
        case -2: {
          // invalid name under the C++ ABI mangling rules
          std::cout << "Invalid name" << std::endl;
          return -1;
        } break;
        case -3: {
          // invalid argument
          std::cout << "Invalid argument to demangle()" << std::endl;
          return -1;
        } break;
     }
     std::cout << demangled << std::endl;
    
     free(demangled);
    
     return 0;
    

    }

提交回复
热议问题