I have a function template, something like this:
Well, we have already started badly ... notice that the function has as% return void
, when it should be T
:
template <typename T>
T suma(T& a, T&b)
{
return a+b;
}
What do I have to say to tell you the type of data I receive?
Since it is a function template, the compiler will be able to determine the type automatically if both parameters are of the same type:
suma(3,4); // especializado para el tipo int
suma(3.0,4.5); // especializado para double
suma(3,3.5); // error, int y double ¿cual elegir?
For the rest of the cases, since you use references, you will not be able to compile in any way (unless you use polymorphism):
struct A
{
A(int valor) : v(valor)
{}
int v;
};
struct B : A
{
B(int valor) : A(valor)
{ }
};
A operator+(A const& a1, A const& a2)
{
return A(a1.v + a2.v);
}
std::ostream operator<<(std::ostream& out, A const& a)
{
return out << a;
}
int main()
{
A a;
B b;
std::cout << suma(a,b);
}
Even so, you will see that the program still does not compile and this is because the compiler can not decide if T
should be A&
or B&
... however compatible both types are. In this case the solution is to expressly indicate the type of specialization to be used:
int main()
{
A a(2);
B b(3);
std::cout << suma<A>(a,b);
// ^^^
}