Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C++ type resulting from addition

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.

like image 668
gil_mo Avatar asked Jan 29 '23 06:01

gil_mo


2 Answers

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));
}
like image 88
Jarod42 Avatar answered Feb 11 '23 04:02

Jarod42


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.

like image 43
Gaurav Sehgal Avatar answered Feb 11 '23 05:02

Gaurav Sehgal