decltype一般用于模板函数,如:
template <typename T>
T sum(T& a,T& b)
{
return a+b;
}
但这样的话两个变量必须类型相同,所以可以这样写:
template <typename A,typename B>
auto sum(A& a,B& b) ->decltype(a+b)
{
return a+b;
}
因为声明函数的时候不知道返回值的类型,必须后置返回类型。
e.g.
#include <iostream>
using namespace std;
template <typename A,typename B>
auto sum(A& a,B& b) ->decltype(a+b)
{
return a+b;
}
int main()
{
int a=1;
long long b=2;
long double c=3.0;
auto d=sum(a,b);
auto e=sum(a,c);
auto f=sum(b,c);
cout<<d<<' '<<sizeof(d)<<endl<<e<<' '<<sizeof(e)<<endl<<f<<' '<<sizeof(f)<<endl;
cout<<7/d<<endl<<7/e<<endl<<7/f;
return 0;
}
output:
(CF IDE)
3 8
4 12
5 12
2
1.75
1.4
(Luogu IDE)
3 8
4 16
5 16
2
1.75
1.4
(有这个差别是因为不同平台的long double位数不同)