Duda functions template

2

The doubt 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 say to tell you the type of data I receive? Is the compiler immediately aware of the type of variables? that is, when I call suma(3,2) if 3.2 are integers, would I already know? Or would I have to tell you in some way that T is a char / int ...?

I do not know if I explain myself, if not, give me a comment and I'll be clearer.

Thanks and best regards.

    
asked by ProgrammerJr 20.04.2018 в 13:56
source

1 answer

2
  

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);
  //               ^^^
}
    
answered by 20.04.2018 / 14:55
source