添加产生的C++类型是什么

gil*_*_mo 4 c++ compiler-errors type-conversion

我收到了"模糊调用"编译错误:

short i;
MyFunc(i+1, i+1);
Run Code Online (Sandbox Code Playgroud)

MyFunc有两个定义 - 一个带两个短裤,另一个带两个浮子.

我写的时候:

MyFunc(i, i+1);
Run Code Online (Sandbox Code Playgroud)

没有错误 - 编译器推断短.

我的问题是,为什么"短"+ 1可能会导致浮点,我怎样才能避免遍历所有代码并添加显式的强制转换,例如:

MyFunc((short)(i+1), (short)(i+1));
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jar*_*d42 5

i+1晋升为intshort是一个较小的整数类型比int.

所以MyFunc(i+1, i+1);是" 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));
}
Run Code Online (Sandbox Code Playgroud)