C++如何优雅的打印出变量类型

2022-02-20  本文已影响0人  crazyhank
方法1:使用C++库自带的typeid函数

一般使用C++库中的typeid函数获取一个变量的类型,不过打印出来的类型不直观,并且它不支持引用类型的变量,也不能区分const变量。

#include <typeinfo>
#include <iostream>
int main()
{
    int a = 100;
    const int b = 101;
    int& lref = a;
    int&& rref = std::move(a);

    std::cout << "int a: type is " << typeid(a).name() << std::endl;
    std::cout << "const int b: type is " << typeid(b).name() << std::endl;
    std::cout << "int& lref: type is " << typeid(lref).name() << std::endl;
    std::cout << "int&& rref: type is " << typeid(rref).name() << std::endl;
    return 0;
}

输出结果:

int a: type is i
const int b: type is i
int& lref: type is i
int&& rref: type is i

方法2:使用boost库中type_id_with_cvr函数(末尾的cvr代表const, variable, reference)

这个方法打印出来的结果就比较优雅了,如下所示:

#include <iostream>
#include <boost/type_index.hpp>

int main()
{
    int a = 100;
    const int b = 101;
    int& lref = a;
    int&& rref = std::move(a);

    std::cout << "int a: type is " << boost::typeindex::type_id_with_cvr<decltype(a)>().pretty_name() << std::endl;
    std::cout << "const int b: type is " << boost::typeindex::type_id_with_cvr<decltype(b)>().pretty_name() << std::endl;
    std::cout << "int& lref: type is " << boost::typeindex::type_id_with_cvr<decltype(lref)>().pretty_name() << std::endl;
    std::cout << "int&& rref: type is " << boost::typeindex::type_id_with_cvr<decltype(rref)>().pretty_name() << std::endl;

    return 0;
}

输出结果:

int a: type is int
const int b: type is int const
int& lref: type is int&
int&& rref: type is int&&

结论:如果想优雅的打印C++变量的类型,请使用boost库提供的type_id_with_cvr模板函数。

上一篇 下一篇

猜你喜欢

热点阅读