C
C++Liliput
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
}
Both the statements marked as "ERROR" throw errors during compilation.
Now I can understand the first error in that a return type cannot be
possibly deduced. But what I don't understand is the second error. Why
is the return type not automatically deduced to be float? Such a
deduction happens for arguments of a function template (in case we
don't specify the data type during template instantiation directly).
Then why cannot it happen for the return type? Is it a compiler bug or
was it intended to be the behavior? If so why? I am using g++ compiler
on Linux.
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
}
Both the statements marked as "ERROR" throw errors during compilation.
Now I can understand the first error in that a return type cannot be
possibly deduced. But what I don't understand is the second error. Why
is the return type not automatically deduced to be float? Such a
deduction happens for arguments of a function template (in case we
don't specify the data type during template instantiation directly).
Then why cannot it happen for the return type? Is it a compiler bug or
was it intended to be the behavior? If so why? I am using g++ compiler
on Linux.