使用流运算符输出 128 位整数

Output 128 bit integer using stream operator

提问人:intrigued_66 提问时间:12/9/2022 最后编辑:phuclvintrigued_66 更新时间:12/10/2022 访问量:240

问:

我使用的是 GCC 的 128 位整数:

__extension__ using uint128_t = unsigned __int128;
uint128_t a = 545;
std::cout << a << std::endl;

但是,如果我尝试使用流运算符输出,则会出现编译器错误:

error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘uint128_t’ {aka ‘__int128 unsigned’})

有没有办法允许这样做?

Linux,GCC 版本 11.1,x86-64

C++ GCC CLANG C++20 int128

评论

1赞 user4581301 12/9/2022
看来你注定要写作std::ostream & operator<<(std::ostream & out, uint128_t val)
0赞 phuclv 12/9/2022
可能的重复: 如何在 g++ 中打印 __int128?,但它不像这样针对 C++20

答:

0赞 Javier 12/9/2022 #1

您将不得不自己重载运算符,因为该类型没有重载,因为它来自外部库。这可能会有所帮助。<<std::ostream

评论

1赞 Pete Becker 12/9/2022
“来自外部库”不是问题;许多外部库为 I/O 定义了适当的运算符重载。问题是这个库没有。
0赞 Javier 12/9/2022
@PeteBecker正确,这就是为什么在使用外部库时应检查运算符重载的原因。
3赞 康桓瑋 12/9/2022 #2

libstdc++ 没有 的重载。但是,您可以使用 C++20 库,它支持 libstdc++ 和 libc++ 的格式。ostream__int128<format>__int128

#include <format>
#include <iostream>

int main() {
  __extension__ using uint128_t = unsigned __int128;
  uint128_t a = 545;
  std::cout << std::format("{}\n", a);
}

演示