回顾typeof和typeid
int a = 0
typeof(a) b = 5
- typeof不是C++标准,是GCC编译器提供的一个获取变量类型的运算符
- c++标准提供typeid运算符获取操作数的类型信息,但typeid不能像typeof一样在编译器确定对象类型
decltype说明符
decltype说明符的语法与typeof相似
int x1 =0;
decltype(x1) x2 = 0;
double x3 =0.0;
decltype(x1+x3) x4 = x1+x3;
- decltype运算符可以在非静态成员中使用,auto不行
decltype用途
在c++14标准后,auto可用于返回值类型推导,但当我们需要返回引用类型时,使用auto进行类型推导会返回值类型,见下面的代码
auto return_ref(int &t){
return t;
}
\\返回值类型为int
未解决上述问题,可搭配decltype做函数返回类型后置
auto return_ref(int &t)->decltype(t){
return t;
}
推导规格
decltype(e)的推导规则有以下5条:
- 如果e是未加括号的标识符表达式或未加括号的类成员访问,delctype(e)推导出的类型为e的类型T
- 如果e是函数调用或者仿函数调用,decltype(e)为其返回值类型
- 如果e是一个左值,decltype(e)为T&
- 如果e是将亡值,decltype(e)为T&&
- 其余情况,decltype(e)为T