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

方法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模板函数。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容