美文网首页
C++如何优雅的打印出变量类型

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

作者: crazyhank | 来源:发表于2022-02-20 17:56 被阅读0次
方法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模板函数。

相关文章

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

    方法1:使用C++库自带的typeid函数 一般使用C++库中的typeid函数获取一个变量的类型,不过打印出来的...

  • C++ 变量和复合类型

    前面说了C++的基本数据类型,下面来看看在C++中如何定义变量和常量。 变量 定义和初始化 C++定义变量的方式和...

  • C++变量类型

    C++ 中的变量定义 变量定义 :告诉编译器在何处创建变量的存储,以及如何创建变量的存储。变量定义指定一个数据类型...

  • 动静、强弱变量类型

    静态类型vs动态类型 静态类型 静态类型是指在编译时就能确定变量类型的类型例如,C++语言中定义变量: 以上变量都...

  • C++ 中的变量

    C++ 中的变量内存数据类型 C++ 数据类型 使用编程语言进行编程时,需要用到各种变量来存储各种信息。变量保留的...

  • C++ Builder 的字符串类型、字符类型、字符编码

    C++ Builder 参考手册 ➙ C++ Builder 的字符串类型、字符类型、字符编码 字符变量 字符常数...

  • C++变量的存储类别

    参考:C++(存储类)经典!! C++存储类(菜鸟教程) C++变量属性 一个变量除了数据类型以外,还有3种属性:...

  • 日更挑战-语言基础汇总-变量定义

    声明和赋值:强类型,弱类型 1. 确定类型 java 变量类型 标识符=值 C/C++ 变量类型 标识符=值 oc...

  • 每天一个知识点(二十)

    C++中void的用法: void的意思就是无类型,void类型的变量或者指针可以接受任何类型变量的赋值。 例:i...

  • C++变量类型

    C++中变量的定义与声明 变量定义就是告诉编译器在何处创建变量的存储,以及如何创建变量的存储。变量定义指定一个数据...

网友评论

      本文标题:C++如何优雅的打印出变量类型

      本文链接:https://www.haomeiwen.com/subject/kejvlrtx.html