I have this code:
template<
class T = const int &
> void f(T) {}
void f(const int &) {}
int main() {
f(0);
}
Why does it call the second one instead of first? I would think of them as being the same but they're clearly not as I do not get a redefinition error.
A template function can be overloaded either by a non-template function or using an ordinary function template.
Templates (normally) require that you use identical syntax to carry out the operations on all (supported) types. Function overloading is (or should be) used similarly, but allows you to use different syntax to carry out the operations for different types.
Function overloading is used when multiple functions do similar operations; templates are used when multiple functions do identical operations. Templates provide an advantage when you want to perform the same action on types that can be different.
You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.
Because the second overload is not a template.
When a template function and a non-template function are both viable for resolving a function call, the non-template function is selected.
From Paragraph 13.3.3/1 of the C++ 11 Standard:
[...] Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...] F1 is a non-template function and F2 is a function template specialization [...]
One is a template and the other is not, they are definitely not the same.
Overload resolution is designed to prefer a non-template over a templated function, everything else being equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With