C++ decltype类型说明符
1基本语法
decltype类型说明符生成指定表达式的类型。在此过程中,编译器分析表达式并得到它的类型,却不实际计算表达式的值。
语法为:
decltype(expression)
编译器使用下列规则来确定expression参数的类型。
如果expression参数是标识符或类成员访问,则decltype(expression)是expression命名的实体的类型。如果不存在此类实体或expression参数命名一组重载函数,则编译器将生成错误消息。
如果expression参数是对一个函数或一个重载运算符函数的调用,则decltype(expression)是函数的返回类型。将忽略重载运算符两边的括号。
如果expression参数是右值,则decltype(expression)是expression类型。如果expression参数是左值,则decltype(expression)是对左值引用类型的expression。
给出如下示例代码:
intvar;
constint&&fx();
structA{doublex;}
constA*a=newA();
语句 类型 注释
decltype(fx()); constint&& 对左值引用的constint
decltype(var); int 变量var的类型
decltype(a->x); double 成员访问的类型
decltype((a->x)); constdouble& 内部括号导致语句作为表达式而不是成员访问计算。由于a声明为const指针,因此类型是对constdouble的引用。
2decltype和引用
如果decltype使用的表达式不是一个变量,则decltype返回表达式结果对应的类型。但是有些时候,一些表达式向decltype返回一个引用类型。一般来说,当这种情形发生时,意味着该表达式的结果对象能作为一条赋值语句的左值:
//decltype的结果可以是引用类型 inti=42,*p=&i,&r=i; decltype(r+0)b;//OK,加法的结果是int,因此b是一个(未初始化)的int decltype(*p)c;//Error,c是int&,必须初始化
因为r是一个引用,因此decltype(r)的结果是引用类型,如果想让结果类型是r所指的类型,可以把r作为表达式的一部分,如r+0,显然这个表达式的结果将是一个具体的值而非一个引用。
另一方面,如果表达式的内容是解引用操作,则decltype将得到引用类型。正如我们所熟悉的那样,解引用指针可以得到指针所指对象,而且还能给这个对象赋值,因此,decltype(*p)的结果类型是int&而非int。
3decltype和auto
处理顶层const和引用的方式不同(参考阅读:C++auto类型说明符)
如果decltype使用的表达式是一个变量,则decltype返回该变量的类型(包括顶层const和引用在内):
constintci=0,&cj=ci; decltype(ci)x=0;//x的类型是constint decltype(cj)y=x;//y的类型是constint&,y绑定到变量x decltype(cj)z;//Error,z是一个引用,必须初始化
decltype的结果类型与表达式形式密切相关
对于decltype所用的引用来说,如果变量名加上了一对括号,则得到的类型与不加括号时会有所不同。如果decltype使用的是一个不加括号的变量,则得到的结果就是该变量的类型;如果给变量加上了一层或多层括号,编译器就会把它当成是一个表达式。
decltype((i))d;//Error,d是int&,必须初始化 decltype(i)e;//OK,e是一个未初始化的int
模板函数的返回类型
在C++11中,可以结合使用尾随返回类型上的decltype类型说明符和auto关键字来声明其返回类型依赖于其模板参数类型的模板函数。
在C++14中,可以使用不带尾随返回类型的decltype(auto)来声明其返回类型取决于其模板参数类型的模板函数。
例如,定义一个求和模板函数:
//C++11
template<typenameT,typenameU>
automyFunc(T&&t,U&&u)->decltype(forward<T>(t)+forward<U>(u))
{returnforward<T>(t)+forward<U>(u);};
//C++14
template<typenameT,typenameU>
decltype(auto)myFunc(T&&t,U&&u)
{returnforward<T>(t)+forward<U>(u);};
(forward:如果参数是右值或右值引用,则有条件地将其参数强制转换为右值引用。)
附上一段源码:
#include<iostream>
#include<string>
#include<utility>
#include<iomanip>
usingnamespacestd;
template<typenameT1,typenameT2>
autoPlus(T1&&t1,T2&&t2)->
decltype(forward<T1>(t1)+forward<T2>(t2))
{
returnforward<T1>(t1)+forward<T2>(t2);
}
classX
{
friendXoperator+(constX&x1,constX&x2)
{
returnX(x1.m_data+x2.m_data);
}
public:
X(intdata):m_data(data){}
intDump()const{returnm_data;}
private:
intm_data;
};
intmain()
{
//Integer
inti=4;
cout<<
"Plus(i,9)="<<
Plus(i,9)<<endl;
//Floatingpoint
floatdx=4.0;
floatdy=9.5;
cout<<
setprecision(3)<<
"Plus(dx,dy)="<<
Plus(dx,dy)<<endl;
//String
stringhello="Hello,";
stringworld="world!";
cout<<Plus(hello,world)<<endl;
//Customtype
Xx1(20);
Xx2(22);
Xx3=Plus(x1,x2);
cout<<
"x3.Dump()="<<
x3.Dump()<<endl;
}
运行结果为:
Plus(i,9)=13 Plus(dx,dy)=13.5 Hello,world! x3.Dump()=42