According to (2)
, ::max(7,42)
should call max<int>
by argument deduction.
No. Think about it, to do overload resolution (aka, to pick the best match), the compiler first needs to know all available overloads and be able to compare them. Note how a function template by itself is not a valid function, it first needs to be instantiated to create a real function.
This means that first, the compiler looks after all function templates named max
, tries template argument deduction for every one of them, and then does overload resolution on the instantiated functions together with the non-template functions.
Here's a visualization of the functions (leaving out cv-qualifiers for brevity):
int max(int, int);
template<class Arg> Arg max(Arg, Arg);
template<class Arg> Arg max(Arg, Arg, Arg);
Let's walk through the invokation ::max(7, 42)
.
First, the compiler sees that there are three candidate functions. However, it can't just compare the first overload of max
to the other two - that'd be like comparing apples and oranges. Instead, it first needs to "stamp out" a real function from the function template blue-prints. This happens, in our case, through template argument deduction:
int max(int, int); // originally non-template
int max(int, int); // originally template
int max(int, int, int); // not enough arguments, invalid
With the third overload being thrown out thanks to mismatching argument / parameter counts, we're down to two. From a perspective of overload resolution, both are equal - but wait! Now a certain rule steps in that says:
§13.3.3 [over.match.best] p1
[...] Given these definitions, a viable function F1
is defined to be a better function than another viable function F2
if [...]:
F1
is a non-template function and F2
is a function template specialization,