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

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

For example:

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

Expected output:

int
21条回答
  •  遇见更好的自我
    2020-11-22 02:09

    In C++11, we have decltype. There is no way in standard c++ to display exact type of variable declared using decltype. We can use boost typeindex i.e type_id_with_cvr (cvr stands for const, volatile, reference) to print type like below.

    #include 
    #include 
    
    using namespace std;
    using boost::typeindex::type_id_with_cvr;
    
    int main() {
      int i = 0;
      const int ci = 0;
      cout << "decltype(i) is " << type_id_with_cvr().pretty_name() << '\n';
      cout << "decltype((i)) is " << type_id_with_cvr().pretty_name() << '\n';
      cout << "decltype(ci) is " << type_id_with_cvr().pretty_name() << '\n';
      cout << "decltype((ci)) is " << type_id_with_cvr().pretty_name() << '\n';
      cout << "decltype(std::move(i)) is " << type_id_with_cvr().pretty_name() << '\n';
      cout << "decltype(std::static_cast(i)) is " << type_id_with_cvr(i))>().pretty_name() << '\n';
      return 0;
    }
    

提交回复
热议问题