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

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

For example:

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

Expected output:

int
21条回答
  •  一整个雨季
    2020-11-22 02:14

    You could use a traits class for this. Something like:

    #include 
    using namespace std;
    
    template  class type_name {
    public:
        static const char *name;
    };
    
    #define DECLARE_TYPE_NAME(x) template<> const char *type_name::name = #x;
    #define GET_TYPE_NAME(x) (type_name::name)
    
    DECLARE_TYPE_NAME(int);
    
    int main()
    {
        int a = 12;
        cout << GET_TYPE_NAME(a) << endl;
    }
    

    The DECLARE_TYPE_NAME define exists to make your life easier in declaring this traits class for all the types you expect to need.

    This might be more useful than the solutions involving typeid because you get to control the output. For example, using typeid for long long on my compiler gives "x".

提交回复
热议问题