4

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.

gil_mo
  • 575
  • 1
  • 6
  • 27

3 Answers3

5

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));
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

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.

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
1

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.

robert
  • 3,539
  • 3
  • 35
  • 56