1

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
intrigued_66
  • 16,082
  • 51
  • 118
  • 189
  • 1
    Looks like you're doomed to writing `std::ostream & operator<<(std::ostream & out, uint128_t val)` – user4581301 Dec 08 '22 at 19:42
  • possible duplicate: [How to print __int128 in g++?](https://stackoverflow.com/q/25114597/995714), but it doesn't target C++20 like this – phuclv Dec 09 '22 at 08:17

2 Answers2

3

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

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
0

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.

Javier
  • 36
  • 4
  • 1
    "from an external lib" isn't the problem; lots of external libraries define appropriate operator overloads for I/O. The problem is that **this** lib doesn't. – Pete Becker Dec 08 '22 at 20:17
  • @PeteBecker correct, that's why operator overloads should be checked among other things when working with external libs. – Javier Dec 08 '22 at 20:26