views:

123

answers:

4

The one advantage of using class T in c++ is to reduce the time to redefine data types in a function, if those data types are defined in other function, for example, in int main.

template <class T>
void showabs(T number)
{
  if (number < 0 )
    number  = -number;
  cout << number << endl;
  return 0;
}

int main()
{
  int num1 = -4;
  float num2 = -4.23f;

  showabs(num1);
  showabs(num2);

  return 0;
}

So in this case, without class T, for each data type, we have to add its corresponding data-type condition, that is, another set of if statement for int, and another one for float.

Am I correct?

+1  A: 

if statements wouldn't help in declaring the type of the number parameter. I think you meant that you would have to overload the showabs function for each type you want to handle. If so, then yes, you are on the right track.

Marcelo Cantos
right, for each type, i have to do another set of if statement, similar to the one we had above, in the function showabs.
JohnWong
+10  A: 

It doesn't have to be class T. It could be class Key or whatever you want (You can also use typename in place of class). The correct term would be function template. Using a function template removes the requirement to redefine a function for every type that may be passed to it. So if you didn't use templates you would have to define two functions:

void showabs(float number){
  if (number < 0 ) number  = -number;
  cout << number << endl;
}

void showabs(int number){
  if (number < 0 ) number  = -number;
  cout << number << endl;
}

Which means a lot of repeated code. You can in some cases use void* pointers (You see this a lot in C), but doing so leads to an ugly interface as well as no type safety.

It is worth noting that in reality, your two function calls

showabs(num1); //showabs<int>(num1);
showabs(num2); //showabs<float>(num2);

Actually point to two different functions, one that takes a float and one that takes an integer. So templates allow the compiler to do the copying and pasting for us (in a lot more intelligent way).

Yacoby
+1  A: 

Well, it is not "the one advantage", there are many others. Templates are made for reusing, so you can use your templated functions or classes for types you did not know when you wrote them.

Gorpik
+1  A: 

Basically, you are correct, but there is a lot more you can do with templates, namely, template-metaprogramming. To clarify on you terminology, class T could also be typename Foo. class T is a template parameter, a function-definition with a template parameter is a function-template and a class-definition with a template parameter is a class-template.

Space_C0wb0y