On 24 Okt., 07:05, "C++Liliput" <aveekmi...@gmail.com> wrote:
> Consider the following code
>
> template<class T1, class T2>
> T2 sum(T1 a, T1 b)
> {
> T2 ret = a + b;
> return ret;
>
> }
>
> int main()
> {
> float f1 = 2, f2 = 3;
> int i1 = 2, i2 = 4;
>
> sum<float>(f1, f2); //ERROR
> float fret = sum<float>(f1, f2); //ERROR
> }
There *is* no type deduction for the return type. But you may do the
following:
template<class T2, class T1> // <-- swapped T1 & T2
T2 sum(T1 a, T1 b)
{
T2 ret = a + b;
return ret;
}
int main()
{
float f1 = 2, f2 = 3;
sum<float>(f1, f2); //OK, T2=float, T1=float (deduced)
}
Cheers,
SG