我收到了“模棱两可的调用”编译错误:
short i;
MyFunc(i+1, i+1);
MyFunc 有两个定义 - 一个接受两个短裤,另一个接受两个 float 。
当我写的时候:
MyFunc(i, i+1);
没有错误 - 编译器推导出 short。
我的问题是,为什么 'short' + 1 可能会导致 float ,我怎样才能避免遍历我的所有代码并添加显式强制转换,例如:
MyFunc((short)(i+1), (short)(i+1));
谢谢。
最佳答案
i+1
被提升为int
作为short
是比 int
更小的整数类型.
所以 MyFunc(i+1, i+1);
是“MyFunc(int, int);
”
您可以通过添加执行预期分派(dispatch)的重载来解决歧义,例如:
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));
}
关于c++ - 加法产生的 C++ 类型是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197717/