为何__int128搭配std::cmp_less在不同C++标准编译选项下表现异常?
问题:__int128 配合 std::cmp_less 在不同编译标准下的编译差异
以下是测试用的C++代码:
#include <cstdint> #include <utility> #include <iostream> int main() { __int128 a = -1; __int128 b = 1; if (std::cmp_less(a, b)) { std::cout << "less" << std::endl; } }
编译现象
- 使用编译选项
-std=gnu++2b(或-std=gnu++20)时,代码可正常编译运行; - 使用
-std=c++20或-std=c++23时,编译失败,报错信息如下:
In file included from <source>:2: /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/utility: In instantiation of 'constexpr bool std::cmp_less(_Tp, _Up) [with _Tp = __int128; _Up = __int128]': <source>:11:18: required from here /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/utility:141:49: error: static assertion failed 141 | static_assert(__is_standard_integer<_Tp>::value); | ^~~~~ /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/utility:141:49: note: 'std::integral_constant<bool, false>::value' evaluates to false /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/utility:142:49: error: static assertion failed 142 | static_assert(__is_standard_integer<_Up>::value); | ^~~~~ /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/utility:142:49: note: 'std::integral_constant<bool, false>::value' evaluates to false Compiler returned: 1
原因解释
- __int128 是 GCC 专属扩展类型:C标准并未定义
__int128,它是GCC为支持128位整数运算提供的非标准扩展,不属于C标准规定的整数类型范畴。 - std::cmp_less 的标准模式检查:
std::cmp_less是C20引入的标准比较函数,在标准编译模式(-std=c++20/c++23)下,GCC的标准库实现会通过__is_standard_integer这个内部类型 trait 做静态断言,确保传入的参数是C标准定义的整数类型(比如int、long long、int64_t等),而__int128不满足这个条件,因此触发断言失败。 - GNU扩展模式的适配:当使用
-std=gnu++xx系列编译选项时,GCC会启用自身的扩展特性,同时对标准库做适配修改——让__is_standard_integer识别__int128为“符合要求的整数类型”,从而绕过静态断言,代码就能正常编译。
内容的提问来源于stack exchange,提问作者Ferenc Deak
相关产品推荐
相关产品推荐

