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
  • 17,981
  • 46
  • 54
  • 68
maciek
  • 1,279
  • 2
  • 13
  • 27
  • 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 `< – 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