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

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

For example:

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

Expected output:

int
21条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 02:16

    The other answers involving RTTI (typeid) are probably what you want, as long as:

    • you can afford the memory overhead (which can be considerable with some compilers)
    • the class names your compiler returns are useful

    The alternative, (similar to Greg Hewgill's answer), is to build a compile-time table of traits.

    template  struct type_as_string;
    
    // declare your Wibble type (probably with definition of Wibble)
    template <>
    struct type_as_string
    {
        static const char* const value = "Wibble";
    };
    

    Be aware that if you wrap the declarations in a macro, you'll have trouble declaring names for template types taking more than one parameter (e.g. std::map), due to the comma.

    To access the name of the type of a variable, all you need is

    template 
    const char* get_type_as_string(const T&)
    {
        return type_as_string::value;
    }
    

提交回复
热议问题