Reputation: 219
In C++, say you have two function definitions:
template <typename T>
T square (T num);
And
double square(double num);
and you have a function call like:
square(1.5);
which function would be called? Which does the compiler choose?
Upvotes: 1
Views: 78
Reputation: 119239
The argument 1.5
is of type double
so it exactly matches both the template and non-template. In such a case the non-template function will be preferred according to [over.best.match] in the standard:
...
F1
is defined to be a better function than ...F2
if ...F1
is not a function template specialization andF2
is a function template specialization ...
If you called square
with an int
or float
argument, the template would again give an exact match but you'd need a conversion or promotion for the non-template. The template would be selected since it's a better match.
Upvotes: 4
Reputation: 10733
In this case C++ always prefers non-template version of function as it could easily promote float to double.
Had you used this:-
float p = 2.2;
square(p);
compiler would have chosen template version in its venture for perfect match.
Upvotes: 2
Reputation: 1458
Since call syntax matches the non-template function, so it will be called
Upvotes: 1