C++中查看某变量的类型 typeid().name()

1. 包含头文件

#include <typeinfo>

2. 返回的数据

Linux-g++ 下直接使用typeid(i).name()的结果如下(不便阅读)int i = 0;
	cout << "i's type is: " << typeid(i).name() << endl;//i's type is: i
	
这是因为,Linux的gcc/g++编译器,只输出类型名的第一个字符
		bool:                     b
		 
		char:                     c
		signed char:              a
		unsigned char:            h
		 
		(signed) short (int):     s
		unsigned short (int):     t
		 
		(signed) (int):           i
		unsigned (int):           j
		 
		(signed) long (int):      l
		unsigned long (int):      m
		 
		(signed) long long (int): x
		unsigned long long (int): y
		 
		float:                    f
		double:                   d
		long double:              e

Linux下输出完整的名字需要:
	./execute | c++filt -t

c++filt -t 对结果进行过滤和解码
Windows下只需要:
	int i = 0;
	cout << "i's type is: " << typeid(i).name() << endl;//i's type is: int

3. Test

#include <iostream>
#include <typeinfo>
using namespace std;

void testP63_decltype()
{
    
    
    int i = 42;
    int *p = &i;
    int &r = i;
    //不使用c++filt -t过滤结果的话
    cout << "i's type is: " << typeid(i).name() << endl;//i's type is: i
    cout << "p's type is: " << typeid(p).name() << endl;//p's type is: Pi
    cout << "r's type is: " << typeid(r).name() << endl;//r's type is: i
    //使用c++filt -t过滤结果的话
    //int'short type is: int
	//p'short type is: int*
	//r'short type is: int
}
int main()
{
    
    
    testP63_decltype();
    return 0;
}

4. 扩展 c++filt

man c++filt
点击看大图(清楚)
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/liangwenhao1108/article/details/105193830