1.decltype关键字获取表达式的类型
int x = 0;
decltype(x) y = 1; //y -> int
2.推导规则decltype(exp)
- exp是标识符、类访问表达式,decltype(exp) 和 exp 类型一致
int n = 0;
volatile const int & x = n;
decltype(n) a = n; //a -> int
decltype(x) b = n; //b -> const volatile int &
- exp是函数调用,decltype(exp)和返回值类型一致
const int& fun_cint_r(void); //左值
const int fun_cint(void); //纯右值
const Foo fun_cfoo(void); //纯右值
int x = 0;
decltype(fun_cint_r()) a1 = x; //a1 -> const int &
decltype(fun_cint()) a2 = 0; //a2 -> int &
decltype(fun_cfoo()) a3 = 0; //a3 -> const Foo
注意:按照规则,decltype的结果和函数的返回值类型保持一致。a2是int而不是const int. 而是因为函数返回的是一个纯右值,对于纯右值而言,只有类类型可以携带cv限定符如a3,此外一般忽略掉cv限定符。
- 其他情况,若exp是一个左值,则decltype(exp)是exp类型的左值引用,否则和exp类型一致
int n = 0, m = 0;
decltype(n + m) c = 0; //c -> int 左值
decltype(n += m) d = c; //d -> int & 纯右值
3.返回类型后置语法
#include <stdio.h>
#include <iostream>
using namespace std;
template <typename T, typename U>
auto add(T t, U u) -> decltype(t + u)
{
return t + u;
}
int& foo(int& i)
{
i = 10;
return i;
}
float foo(float& f)
{
float temp = 1.25;
f = 5;
temp += f;
return temp;
}
template <typename T>
auto func(T& val) -> decltype(foo(val))
{
return foo(val);
}
int main()
{
float a = 0, b = 0, sum = 0;
printf("累加计算器...请输入值:\n");
scanf("%f,%f",&a,&b);
sum = add(a, b);
printf("累加后的和: %f\n", sum);
float input = 2.3;
auto result = func(input);
cout<<"result="<<result<<",input="<<input<<endl;
int iInput = 1;
auto iResult = func(iInput);
cout<<"result="<<iResult<<",input="<<iInput<<endl;
return 0;
}
学习文献:
《深入应用C++11》