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

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

For example:

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

Expected output:

int
21条回答
  •  再見小時候
    2020-11-22 02:12

    I like Nick's method, A complete form might be this (for all basic data types):

    template  const char* typeof(T&) { return "unknown"; }    // default
    template<> const char* typeof(int&) { return "int"; }
    template<> const char* typeof(short&) { return "short"; }
    template<> const char* typeof(long&) { return "long"; }
    template<> const char* typeof(unsigned&) { return "unsigned"; }
    template<> const char* typeof(unsigned short&) { return "unsigned short"; }
    template<> const char* typeof(unsigned long&) { return "unsigned long"; }
    template<> const char* typeof(float&) { return "float"; }
    template<> const char* typeof(double&) { return "double"; }
    template<> const char* typeof(long double&) { return "long double"; }
    template<> const char* typeof(std::string&) { return "String"; }
    template<> const char* typeof(char&) { return "char"; }
    template<> const char* typeof(signed char&) { return "signed char"; }
    template<> const char* typeof(unsigned char&) { return "unsigned char"; }
    template<> const char* typeof(char*&) { return "char*"; }
    template<> const char* typeof(signed char*&) { return "signed char*"; }
    template<> const char* typeof(unsigned char*&) { return "unsigned char*"; }
    

提交回复
热议问题