The one advantage of using class T in 开发者_如何学Cc++ 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?
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).
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.
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.
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.
精彩评论