What is the C ++ type associated with adding

I get a "ambiguous call" compilation error for this:

short i;
MyFunc(i+1, i+1);

Where there are two definitions for MyFunc - one of two short circuits, the other - two floats.

When I write:

MyFunc(i, i+1);

No error - the compiler prints short.

My question is: how did it happen that short + 1 can appear as a floating point, and how can I avoid going to all my code and adding explicit tricks, such as:

MyFunc((short)(i+1), (short)(i+1));

Thank.

+4
source share
3 answers

i+1rises to int, since it shortis a smaller integral type than int.

therefore MyFunc(i+1, i+1);there is a " MyFunc(int, int);"

, , , :

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));
}
+5

short , int. MyFunc(int,int) MyFunc(short,short) MyFunc(float,float), , .

+2

, int, int, i + 1 int. . . float.

+1

Source: https://habr.com/ru/post/1688990/


All Articles