为什么 int
到 int64_t
与 int
到 double
的隐式转换不明确?
我原以为积分重载会优先于浮点积分?
#include <stdint.h>
void foo(double) {}
void foo(int64_t) {}
int main()
{
foo(5);
return 0;
}
main.cpp: In function ‘int main()’: main.cpp:8:10: error: call of overloaded ‘foo(int)’ is ambiguous foo(5); ^ main.cpp:3:6: note: candidate: void foo(double) void foo(double) {} ^ main.cpp:4:6: note: candidate: void foo(int64_t) void foo(int64_t) {} ^
我的环境是:
- x86_64
- g++-5.4(使用
-std=c++14
)
int64_t
在我的机器上是一个long int
:
/usr/include/stdint.h
:
# if __WORDSIZE == 64
typedef long int int64_t;
# else
我已经在我的测试应用程序中用静态断言确认了这一点:
static_assert(__WORDSIZE == 64, "");
static_assert(std::is_same<int64_t, long int>::value, "");
我的构建标志是:
-std=c++14 -Werror -Wall -Wextra -m64 -msse2 -msse4.2 -mfpmath=sse
-ftemplate-depth-128 -Wno-unused-parameter -pthread -g -ggdb3 -O0 -fno-inline
最佳答案
从 [over.ics.user] 表 12 我们有
如您所见,整数和 float 提升具有相同的等级,整数和 float 转换具有相同的等级。
现在我们需要确定 5 -> int64_t
是整数提升还是转换。如果我们检查 [conv.prom]/1 我们发现
A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.
提升在 int
处停止,因此我们必须查看 [conv.integral]/1,这是整数转换,我们有
A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type.
这是怎么回事。所以 5 -> int64_t
是整数转换,5 -> double
是 float 转换,它们的排名相同,所以重载解析是不明确的。
关于c++ - 重载不明确(int -> int64_t vs int -> double),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38772637/