1. 使用函数返回类型后置声明函数
auto fun() -> int; // 等同于 int fun();
在上述代码中,auto只是一个占位符,函数名后->紧跟的int才是真正的返回类型;在返回值类型比较复杂的时候使用返回类型后置比较方便。
#include <iostream>
using namespace std;
int fun1(int x)
{
return x * 10;
}
typedef int(*Fun)(int);
Fun fun2()
{
return fun1;
}
//int(*Fun)(int) fun3() // 编译失败
//{
// return fun1;
//}
auto fun4() -> int(*)(int)
{
return fun1;
}
int main()
{
auto fun = fun4();
cout << fun(55) << endl;
return 0;
}
2.推导函数模板返回类型
自动推导函数返回类型:
using namespace std;
template <typename T1, typename T2>
auto add(T1 x, T2 y) -> decltype(x + y)
{
return x + y;
}
int main()
{
auto res = add(15, 2.36);
cout << res << endl;
return 0;
}