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));
}
During addition, if operands are smaller than int
, they are promoted to int
and the result of i + 1
is also an int
. For more check this link . At this point during overload resolution an integral to float type conversion occurs.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.