![](/img/trans.png)
[英]Getting results from functions with 'void' return type, while resulting variable is one of the input arguments - C++
[英]What is the C++ type resulting from addition
我收到了“模糊调用”编译错误:
short i;
MyFunc(i+1, i+1);
MyFunc有两个定义 - 一个带两个短裤,另一个带两个浮子。
我写的时候:
MyFunc(i, i+1);
没有错误 - 编译器推断短。
我的问题是,为什么“短”+ 1可能会导致浮点,我怎样才能避免遍历所有代码并添加显式的强制转换,例如:
MyFunc((short)(i+1), (short)(i+1));
谢谢。
i+1
被提升为int
因为short
是比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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.