#《C++11新特兴—C++标准库的更新》

##特性2:返回类型后置

1、使用场景

主要用于一些可能需要通过参数的运算来得到返回值的类型。例如如下场景: auto z1 = add<decltype(x + y), int, double>(x, y);中如果在使用时要传入返回值类型就必须知道函数中做了哪些操作,这样才能知道返回值的类型,但往往在调用时并不知道里面做什么操作!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
// R->返回值类型, T->参数1类型, U->参数2类型
template <typename R, typename T, typename U>
R add(T t, U u)
{
return t + u;
}

int main()
{
int x = 520;
double y = 13.14;
auto z1 = add<decltype(x + y), int, double>(x, y);
auto z = add<decltype(x + y)>(x, y); // 简化之后的写法
cout << "z: " << z << endl;
return 0;
}

因此对于上述的问题解决方案就是通过自动类型推导,但不能使用auto因为其只能根据值进行推导,所以采用decltype,但是decltype放在返回值位置也不能推导(因此此时参数还没被定义),所以将其放在函数参数后面,称为类型后缀,此外返回值位置还需要一个关键字因此**放置auto**。

==C++11中增加了后置类型后置语法,其实就是将decltypeauto结合起来完成的返回类型的推导。==

2、使用方法

1
auto func(参数1,参数2,...)->decltype(参数表达式)

此时auto会追踪decltype()推导出来的类型。

一个很好的案例:

1
#include <iostream>using namespace std;int& test(int &i){    return i;}double test(double &d){    d = d + 100;    return d;}template <typename T>// 返回类型后置语法auto myFunc(T& t) -> decltype(test(t)){    return test(t);}int main(){    int x = 520;    double y = 13.14;    // auto z = myFunc<int>(x);    auto z = myFunc(x);             // 简化之后的写法    cout << "z: " << z << endl;    // auto z = myFunc<double>(y);    auto z1 = myFunc(y);            // 简化之后的写法    cout << "z1: " << z1 << endl;    return 0;}

输出结果:

1
// 输出结果z: 520z1: 113.14