The question is clear and concise, I have a function template, something like this:
template <typename T>
T suma(T& a, T&b)
{
return a+b;
}
The question is, what do I have to put to tell it the type of data I receive? Does the compiler immediately know by the type of the variables? that is, when I call suma(3,2)
if 3,2 are integers, would you already know? Or would I have to tell it somehow that T is a char/int type...?
I don't know if I explain myself, if not, give me a comment and I'll be clearer.
Thanks and regards.
Well, we already started badly... notice that the function has as return type
void
, when it should beT
:Since it is a function template, the compiler will be able to determine the type automatically if both parameters are of the same type:
For the rest of the cases, since you use references, you will not be able to compile in any way (unless you use polymorphism):
Even so, you will see that the program still does not compile and this is because the compiler cannot decide if it
T
should beA&
orB&
... no matter how compatible both types are. In this case, the solution is to expressly indicate the type of specialization to use: