问题
I have an overloaded template function:
template<typename T1, typename T2>
auto overMax(T1 a, T2 b)
{
std::cout << __FUNCSIG__ << std::endl;
return b < a ? a : b;
}
template<typename RT, typename T1, typename T2>
RT overMax(T1 a, T2 b)
{
std::cout << __FUNCSIG__ << std::endl;
return b < a ? a : b;
}
If I call it like this:
auto a = overMax(4, 7.2); // uses first template
auto b = overMax<double>(4, 7.2); // uses second template
everything works perfect, but
auto c = overMax<int>(4, 7.2); // error
causes ambiguous call.
Why is it so with int, and OK which other types?
回答1:
RT
is non deducible, so when not providing it, only template<typename T1, typename T2>
auto overMax(T1 a, T2 b)
can be called.
When you (partially) provide one template argument, both methods are viable,
but depending of argument, one can be a better candidate:
For
auto b = overMax<double>(4, 7.2); // uses second template
Both
overMax<double, int, double>
andoverMax<double, double>
are viable.
ButoverMax<double, int, double>
is exact match
whereasoverMax<double, double>
requiresint
todouble
conversion.For
auto c = overMax<int>(4, 7.2); // Ambiguous call
Both
overMax<int, int, double>
andoverMax<int, double>
are viable.
But neither is a better match or more specialized, so the call is ambiguous.
来源:https://stackoverflow.com/questions/59752045/auto-return-type-of-template-and-ambiguity