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

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

For example:

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

Expected output:

int
21条回答
  •  抹茶落季
    2020-11-22 02:10

    You can use templates.

    template  const char* typeof(T&) { return "unknown"; }    // default
    template<> const char* typeof(int&) { return "int"; }
    template<> const char* typeof(float&) { return "float"; }
    

    In the example above, when the type is not matched it will print "unknown".

提交回复
热议问题