提问人:intrigued_66 提问时间:12/9/2022 最后编辑:phuclvintrigued_66 更新时间:12/10/2022 访问量:240
使用流运算符输出 128 位整数
Output 128 bit integer using stream operator
问:
我使用的是 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
答:
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);
}
评论
std::ostream & operator<<(std::ostream & out, uint128_t val)