C++ 获取变量类型 decltype 和 (typeid().name)

前言

在C++11中新增了一个关键字decltype,其功能是在编译时期进行自动类型推导,与auto类似,但是两者的具体使用方式不同。
decltype 全称 declare type,意思是 “声明类型”

具体用法

代码示例:

int exp = 1;
decltype(exp) newExp = exp;

从示例中,我们可以知道decltype的作用是推导出某一变量的类型,并以此类型声明一个变量和赋值;

但是decltype不仅仅只是这个作用;

decltype(exp) variableName = value;

这里的exp代表一个表达式,variableName是变量名,value是值;
decltype根据表达式(exp)推导出的数据类型去声明一个变量并赋值;

推导规则

decltype的推导规则有三条

  1. 如果表达式(exp)不被括号包含,且它是一个单独的变量、类成员访问表达式,那么decltype推导出的类型和表达式类型一直;
  2. 如果表达式(exp)是函数调用,那么decltype推导出的类型和函数返回值的类型一致;
  3. 如果表示式(exp)是一个左值,或者是被括号包含,那么decltype推导出的类型就是表达式(exp)的引用(T&);

代码示例

规则一
// 单独变量
	int exp = 0;
	const int &r = exp;
	decltype(exp) a = exp; // exp的类型为 int, a的类型为 int
	decltype(r) b = exp;   // r的类型为 const int& , b 的类型为 const int&

// 类成员访问表达式
	class people
	{
	public:
		string name;
		int age;
	}

	people p;
	decltype(p.name) child = "cxk"; // 类成员变量name的类型为string, child的类型为string
规则二
int function(int a);                      // 返回值为 int
int& function(string b);                  // 返回值为 int&
int&& funciton(int a, int b);             // 返回值为 int&&
const int& function(int a, int b, int c); // 返回值为 const int&
const int&& function(void);               //返回值为 const int&&

int n = 100; 
decltype(function(100)) a = n;      //a 的类型为 int 
decltype(function("ss")) a = n;     //a 的类型为 int& 
decltype(function(1,2)) b = 0;      //b 的类型为 int&& 
decltype(function(1,2,3)) x = n;    //x 的类型为 const int & 
decltype(function()) y = 0;         // y 的类型为 const int&&
规则三
class Sample
{ 
public: 
	int x; 
};

Sample obj;
decltype(obj.x) a = 0;   //obj.x 为类的成员访问表达式,符合推导规则一,a 的类型为 int
decltype((obj.x)) b = a; //obj.x 带有括号,符合推导规则三,b 的类型为 int&。

int n = 0, m = 0;
decltype(n + m) c = 0;     //n+m 得到一个右值,符合推导规则一,所以推导结果为 int
decltype(n = n + m) d = c; //n=n+m 得到一个左值,符号推导规则三,所以推导结果为 int&

// 一个错误示例
int function(int a, int b)
{
    return 0;
}

decltype(function(1, 2)) a = 1;  
decltype((function(1, 2))) b = a;
// 以上两条 decltype(exp)都是int
// 这里第二条不满足规则三

扩展

C++有一个typeid运算符能够在运行时获取类型的信息,但是其返回的字符串会受到编译器的影响。

typeid(int).name()

不同编译器返回的字符串可能不同

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一直在找资料的菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值