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

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

For example:

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

Expected output:

int
21条回答
  •  天涯浪人
    2020-11-22 02:30

    According to Howard's solution, if you don't like the magic number, I think this is a good way to represent and it looks intuitive:

    #include 
    
    template 
    constexpr auto type_name() noexcept {
      std::string_view name = "Error: unsupported compiler", prefix, suffix;
    #ifdef __clang__
      name = __PRETTY_FUNCTION__;
      prefix = "auto type_name() [T = ";
      suffix = "]";
    #elif defined(__GNUC__)
      name = __PRETTY_FUNCTION__;
      prefix = "constexpr auto type_name() [with T = ";
      suffix = "]";
    #elif defined(_MSC_VER)
      name = __FUNCSIG__;
      prefix = "auto __cdecl type_name<";
      suffix = ">(void) noexcept";
    #endif
      name.remove_prefix(prefix.size());
      name.remove_suffix(suffix.size());
      return name;
    }
    

    Demo.

提交回复
热议问题