0

I am trying to overload the << operator for my C++ class called Box. It is not trivial and inside the definition I have to access the stdout object of type FILE* which is corresponding to the std::cout. I need exactly this object since the interface of another code I will use in my operator (GNU MPFR library) requires this particular one. How can I extract it?

Simplified version below:

std::ostream& operator<<(std::ostream &os, const Box &box) {
    x = ??? // get the stdout from os
    mpfr_out_str(x, 10, 0, box.number, MPFR_RNDN);
    return os;
}
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
maciek
  • 1,807
  • 2
  • 18
  • 30
  • 1
    Use `fopencookie` and stream to `os` on linux. The most _portable_ way - create `mktemp()` a temporary `FILE*`, write to it, `rewind()` then `read()` to a buffer, then output to `os`. As for `How can I extract it?` the general answer is "don't". – KamilCuk Jan 19 '21 at 20:29
  • 1
    `ostream` is not necessarily connected to a file, it could for example be a `ostringstream`. – Werner Henze Jan 19 '21 at 20:35
  • 1
    This seems like asking for trouble. What if the `ostream` in question does not have an underlying `FILE *`? You cannot rely on the first argument to be specifically `std::cout`. If you must overload `<<` then `mpfr_out_str()` may not be an option for you. Or perhaps it's overloading `<<` that you should give up on -- you could always write an ordinary method that takes the needed `FILE *` as an argument. Of course, that mainly just pushes the problem off on the clients of your `Box`. – John Bollinger Jan 19 '21 at 20:35
  • 1
    You might consider `mpfr_get_str` to format a string and then output that. https://www.mpfr.org/mpfr-current/mpfr.html#mpfr_005fget_005fstr – Retired Ninja Jan 19 '21 at 20:41

0 Answers0