C++ 关键字decltype

decltype (expression) var;    // C++11

  decltype是C++11新增的关键字

expression:

  1. 未用空号括起的标识符:var类型等于标识符类型
    int a;
    decltype (a) var;    // var type int
  2. 函数调用:var类型等于返回类型
    int sum(int, int);
    decltype (sum(1, 2)) var;    // var type int
    

      不会实际调用函数,编译器仅查看原型来返回类型

  3. 左值:var为指向其类型的引用
    double xx = 4.4;
    decltype ((xx)) r2 = xx;    // r2 is double &
    decltype (xx) w = xx;    // w is double (Stage 1 match)
    

      如果是标识符,则要求是用括号括起的标识符(什么是左值见“C++引用”)(字符串不大清楚,待候补)

  4. 其它情况:var类型等于expression类型(如表达式:1+2、a+b等)

结合typedef可方便多次声明:

typedef decltype(x +y) xytype;
xytype xpy = x + y;    // 声明变量 
xytype arr[10];    // 声明数组
xytype & rxy = arr[2];    // 声明引用,rxy是arr第三个元素arr[2]的引用

  

原文地址:https://www.cnblogs.com/suui90/p/12991343.html