c++ std::cmp_less对__int128的错误行为取决于标准编译器开关

rjjhvcjd  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(127)

以下简短节目

#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


有人能解释一下为什么会发生这种情况吗?
https://gcc.godbolt.org/z/WYMjjsenP

jgovgodb

jgovgodb1#

由于__int128不是标准的C++整型,因此该类型没有std::cmp_less模板重载。您可以添加这样的重载。

#include <cstdint>
#include <iostream>
#include <utility>

template <>
bool std::cmp_less<__int128, __int128>(__int128 t, __int128 u) {
    return t < u;
}

int main() {
    __int128 a = -1;
    __int128 b = 1;

    if (std::cmp_less(a, b)) {
        std::cout << "less" << std::endl;
    }
}

字符串
https://gcc.godbolt.org/z/o3K9Yzfr4
如果要为不同的TU类型添加重载,请参阅可能实现的示例。

vohkndzv

vohkndzv2#

__int128不是一个标准类型,所以当你在严格标准模式(-std=c++20)下时,它不会工作。唯一的惊喜是,它不会在ab的声明上给出给予错误。
您需要启用GNU扩展(使用-std=gnu++20或类似的扩展)才能使其工作,正如您已经发现的那样。

相关问题