gcc 使用 long 而不是 __int128 实例化模板

gcc instantiates template with long instead of __int128

我很茫然,很迷茫。第二次调用我的 big 模板时发生了什么?

template <class T> void big(T t) {  }

int main()
{
    big(9223372036854775808);                        // calls big<__int128>
    big(941832094813209483120);                      // calls big<long>
    big(239120938091238093219203810293801923832019); // calls big<__int128>
}

为什么长模板实例化为941832094813209483120,而其他两个值得到__int128模板.

这个值显然 适合 long 并且似乎会导致溢出(参见下面的完整 gdb 会话):

big<long> (t=1048147054022350704) at blob.cpp:1

我用 gcc-5.2.0gcc-4.9.2 观察到这一点,而我使用 gdb-7.7.1 进行调试。

这是我的完整 gdb 会话:

Breakpoint 1, main () at blob.cpp:5
(gdb) s 
big<__int128> (t=0x00000000000000008000000000000000) at blob.cpp:1
(gdb)  
main () at blob.cpp:6
(gdb)  
big<long> (t=1048147054022350704) at blob.cpp:1
(gdb)  
main () at blob.cpp:7
(gdb)  
big<__int128> (t=0x0000000000000000d90567828f8ae8d3) at blob.cpp:1
(gdb)

由于 OP 已经确认 long long 在他们的系统上是 64 位的,我们可以看到 gcc docs on 128-bit Integers 说:

There is no support in GCC for expressing an integer constant of type __int128 for targets with long long integer less than 128 bits wide.

所以虽然我同意这种行为很奇怪,但从技术上讲这不是错误,因为 gcc 不支持这种情况并明确记录了这一点。

编译器可能支持扩展的有符号整数,来自 C++11 标准草案第 3.9.1 节:

There may also be implementation-defined extended signed integer types

但它们是实现定义的,在第 2.14.2 节中整数文字的措辞说:

If an integer literal cannot be represented by any type in its list and an extended integer type (3.9.1) can represent its value, it may have that extended integer type [...]

重点可能