Reputation: 237
I am testing the following code with c++ templates. I have written a square function using int and float and with a function template.
#include <iostream>
using namespace std;
int square (int a){
cout << "int function" << endl;
return a*a;
};
float square (float a){
cout << "float function" << endl;
return a*a;
};
template <typename T>
T square (T x){
cout << "template function" << endl;
return x*x;
}
int main(){
cout << square<int>(5) << endl;
cout << square<float>(5.5) << endl;
cout << square(5) << endl;
cout << square(5.5) << endl;
return 0;
}
The output is
template function
25
template function
30.25
int function
25
template function
30.25
though I expected
template function
25
template function
30.25
template function
25
template function
30.25
Can someone explain the difference ?
Upvotes: 0
Views: 527
Reputation: 320719
Template does not "override" regular function. Quite the opposite, regular functions usually "win" the overload resolution process, if they match argument types specified in the call. So, it is actually the other way around: all other things being equal, regular function "overrides" template function.
In your case the first two calls go to templates because you explicitly requested templates by using <>
in the call. You explicitly prohibited the compiler to use regular functions.
The third call goes to the regular function, since it is an exact match and therefore it "wins", as I stated above.
The fourth call goes to the template version since the existing regular function is not an exact match (float
parameter vs. double
argument), while the template can be used to generate an exact match.
Upvotes: 4
Reputation: 170203
It doesn't override anything, it's a better match. That is because 5.5
is a constant of type double
, and not of type float
.
You don't have any overload for doubles so the template gets instantiated. That's because the template doesn't require a conversion sequence from a double to a float, as opposed to your overload.
If you use a float
constant, like so:
cout << square(5.5f) << endl;
It will print
float function
Upvotes: 5