简体   繁体   中英

Output 128 bit integer using stream operator

I'm using GCC's 128 bit integer:

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

However, if I try to output using the stream operator I get the compiler error:

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

Is there a way to allow this?

Linux, GCC version 11.1, x86-64

libstdc++ does not have an ostream overload for __int128 . However, you can use C++20 <format> library, which supports __int128 formatting in both libstdc++ and libc++.

#include <format>
#include <iostream>

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

Demo

You will have to overload the << operator yourself because std::ostream doesn't have an overload for that type as it is from an external lib. This could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM