简体   繁体   中英

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.

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

正如这里所解释的那样在算术运算中使用short时,必须首先将其转换为int 。因此,编译器实际上正在尝试找到正确的MyFunc(int,int)并且必须在MyFunc(short,short)MyFunc(float,float) MyFunc(short,short)之间进行选择。 MyFunc(float,float) ,因此模棱两可。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM