Search code examples
c++templatestemplate-argument-deduction

There seems to be a contradiction in the book "C++ Templates - The Complete Guide"


In Section 2.4 Overloading Function Templates of the book "C++ Templates - The Complete Guide" you'll find the following example:

// maximum of two int values
inline int const& max (int const& a, int const& b)
{
    return a < b ? b : a;
}
// maximum of two values of any type
template <typename T>
inline T const& max (T const& a, T const& b)
{
    return a < b ? b : a;
}
// maximum of three values of any type
template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
    return max (max(a,b), c);
}
int main()
{
    ::max(7, 42); // calls the nontemplate for two ints (1)
}

However in B.2 Simplified Overloading Resolution of Appendix B, the author states:

Note that overload resolution occurs after template Argument deduction, ... (2)

According to (2), ::max(7,42) should call max<int> by argument deduction.


Solution

  • After template argument deduction overload resolution occurs between

    1) inline int const& max (int const& a, int const& b);
    

    and

    2) template <>
       inline int const& max (int const& a, int const& b)
    

    In this situation 1) is called as specified in C++ standard 13.3.3 par. 1 (Draft n3092).

    Msdn also clearly states it:

    If a nontemplate function is an equally good match to a template function, the nontemplate function is chosen

    http://msdn.microsoft.com/en-us/library/s016dfe8%28v=vs.80%29.aspx