C++11可以通过结合auto和decltype来动态的声明函数的返回值类型:
#include <iostream>
using namespace std;
template<class T1, class T2>
auto add(T1 t1, T2 t2) -> decltype(t1 + t2)
{
return t1 + t2;
}
int main(){
auto a = add(5, 1.66);
cout<<"a="<<a<<" type is:"<<typeid(a).name()<<endl;
return 0;
}
运行程序输出:
a=6.66 type is:d
C++14可以通过更为简化的方式,只通过auto来动态的声明函数的返回值类型:
#include <iostream>
using namespace std;
template<class T1, class T2>
auto add(T1 t1, T2 t2)
{
return t1 + t2;
}
int main(){
auto a = add(5, 1.66);
cout<<"a="<<a<<" type is:"<<typeid(a).name()<<endl;
return 0;
}
运行程序输出:
a=6.66 type is:d
在lamdba函数中可以将参数声明为auto:
#include <iostream>