return type deduction for a function template

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.
 
S

SG

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
 
J

James Kanze

I'm afraid the answer is "because the language was designed
to not to support this". (That it's not impossible to do
this can be seen in other languages.)

Other languages are other languages. I'm not sure it would work
that well in C++. (Amongst other things, it would offer yet
another possibility for ambiguity in overload resolution. I
hope you're not going to argue that overload resolution is too
simple in C++, and needs to be made more complicated:).)

It's possible to do in C++, in specific cases where it makes
sense. Just have the class return a proxy object with a

template< typename T > Proxy::eek:perator T() const ;

function.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top