c++ - 加法产生的 C++ 类型是什么

标签 c++ compiler-errors type-conversion

我收到了“模棱两可的调用”编译错误:

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/

相关文章:

c++ - 对 pthreads 感到困惑

c++ - 检查 EnumDisplayDevices dwFlags

c++ - 对重载运算符参数进行隐式转换时出现编译器错误

jenkins - 如何检查特定字符串的控制台输出并在构建时引发错误?

c++ - 创建具有构造函数的单例类,该构造函数接受运行时评估的参数

检查C中的输入类型

c++ - 正则表达式在 C++ 代码中的 '=' 周围添加空格,我做错了什么?

java - 如何将字符串 yyyy-MM-ssThh-mm-ss 转换为 LocalDataTime yyyy-MM-ss hh-mm-ss?

具有特定类型的 List 上的 C# 扩展方法

c++ - 将 int[][] 分配给 int**