I'm getting the "ambiguous call" compilation error for this:
short i;
MyFunc(i+1, i+1);
Where there are two definitions for MyFunc - one taking two shorts, the other taking two floats.
When I write:
MyFunc(i, i+1);
There's no error - the compiler deduces short.
My question is, how come 'short' + 1 may result as a floating point, and how can I avoid going over all my code and adding explicit casts such as:
MyFunc((short)(i+1), (short)(i+1));
Thanks.
i+1
is promoted to int
as short
is a smaller integral type than int
.
so MyFunc(i+1, i+1);
is "MyFunc(int, int);
"
You might resolve the ambiguity by adding overload which does the dispatch expected, something like:
void MyFunc(short, short);
void MyFunc(float, float);
template <typename T1, typename T2>
std::enable_if<std::is_floating_point<T1>::value ||
std::is_floating_point<T2>::value>
MyFunc(T1 t1, T2 t2)
{
MyFunc(static_cast<float>(t1), static_cast<float>(t2));
}
template <typename T1, typename T2>
std::enable_if<!std::is_floating_point<T1>::value &&
!std::is_floating_point<T2>::value>
MyFunc(T1 t1, T2 t2)
{
MyFunc(static_cast<short>(t1), static_cast<short>(t2));
}
As explained here when using short
in arithmetic operations, it must be first converted into an int
.So actually the compiler is trying to find the correct MyFunc(int,int)
and has to choose between MyFunc(short,short)
and MyFunc(float,float)
, hence the ambiguity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With