dimanche 23 mai 2021

Overloading Function Templates

The following example is extracted from the book "C++ Templates - The Complete Guide":

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;
}    

And then it reads:

Now, we can call max(), for example, as follows:

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

However, when calling:

auto c = ::max<int>(4, 7.2); // ERROR: both function templates match

both templates match, which causes the overload resolution process normally to prefer none and result in an ambiguity error.

I understand that both templates match on "c" (::max<int>). Although, I tested the code on Clang, GCC and MSVC and in all of them it compiled just fine without warnings. And it seems that both templates also match "b" (::max<long double>), not only the second one (https://godbolt.org/z/f7TqEhh7o). Why the authors say that only in "c" both function templates match?

Aucun commentaire:

Enregistrer un commentaire