Search code examples
c++templatesoverload-resolutionfunction-templates

Overloading Function templates Rules


The following snippet is from the book C++ templates 2nd edition.

template<typename T1, typename T2>
auto max (T1 a, T2 b)
{
return b < a ? a : b;
}
template<typename RT, typename T1, typename T2>
RT max (T1 a, T2 b)
{
return b < a ? a : b;
}

auto b = ::max<long double>(7.2, 4); // uses second template

My question is why ::max(7.2, 4) used the second template? Shouldn't both function templates match since long double can be the type of T1 or RT? Any hints? Thanks!


Solution

  • For the 1st overload, if T1 is specified as long double, and pass 7.2 which is a double, the implicit conversion from double to long double is required. For the 2nd overload, RT is specified as long double, and T1 will be deduced as double, so it's an exact match and wins in overload resolution.

    If you specify template argument as double as ::max<double>(7.2, 4);, both of them are exact match and the call will be ambiguous.