decltype 是C++11新增的一个关键字,用于使编译器在编译期找出表达式的类型,这其实就是常被要求的typeof 的特性的体现,但由于原有的 typeof 缺乏一致性又不完全,所以才引用这个关键字。
其格式为:
decltype(exp) temp = value ;
decltype的推导规则
如果 exp 是一个不被括号 () 包围的表达式,或者是一个类成员访问表达式,或者是一个单独的变量,temp 的类型和exp一致
如果 exp 是函数调用,则 temp 的类型就和函数返回值的类型一致
如果 exp 是一个左值,或被括号()包围,decltype(exp)的类型就是exp的引用。
如:
当 exp 为一个变量,则返回该变量的类型(包括顶层的 const 和引用)
当 exp 为一个函数时,编译器并不会实际调用函数,而是当调用发生时使函数的返回值类型作为temp 的类型。
当 exp 为一个表达式时,则返回表达式计算后的类型。
当 exp 为一个解引用 *** 作,则 temp 类型为引用。
例如:
int num() { return 0; }
int main(void)
{
int a = 1, * pa = &a, & b = a;
decltype(b)c = a;//c类型为 int& ,需初始化
decltype(b + 0)d = a;// d类型为 int
decltype(*pa)e = a;//e类型为int&,需初始化
double x=1.0;
decltype(num()) f = x;//f类型仍为int
const int a = 10;
const int& b = a;
decltype(a)x = a;//x类型为 const int
decltype(b)y = b;//y类型为 const& int
}
decltype 本身拥有一层(),这是得到 exp 的类型,若是使用 (()) ,编译器就将其认为成一个表达式,则得到的类型为引用。
如下:
int a = 1;
decltype(a) b;//b类型为 int
decltype((a)) c = a;//c类型为 int&
原则上,exp 可以为任何复杂类型,但必须保证 exp 的结果是有类型的,不能是 void 类型,如果
exp 为 void 类型的函数,exp 的结果也是 void 则会造成编译错误。
auto 与 decltype 的区别
auto根据 = 右边的初始值推导出变量的类型,decltype根据exp表达式推导出变量的类型,跟 赋值号( = )右边的value没有关系
auto要求变量必须初始化,这是因为auto根据变量的初始值来推导变量类型的,如果不初始化,变量的类型也就无法推导,decltype则对此不做要求。
例如:类的静态成员可以使用 auto 进行推导,但是对于非静态成员则无法使用 auto,若是想要推导类的非静态成员类型,则只能使用 decltype。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)