1

When writing an overload for the iostream << operator, particularly on an application class, it may be desirable to alter the behavior of that overload based on the standard manipulators in effect on that stream object. Can the state of standard manipulators of a stream be polled from within implementations of << overloads?

For example it might be desirable for

std::cout << std::internal << myClassReference;

to behave differently than

std::cout << std::left << myClassReference;

beyond the differences the custom overload of << may be handing off to member <<'s in its implementation.

If the manipulator state of an iostream can be polled, how is this accomplished? Also what should someone implementing custom manipulators do so that the state of their manipulators can likewise be polled?

Ken Clement
  • 748
  • 4
  • 13

1 Answers1

2

Polling a c++ stream for its formatting state can be accomplished with the flags() function of the std::ios_base class, from which all c++ streams inherit.

The flags function comes in two varieties: a const polling function called with stream.flags(), and a setting function called with stream.flags(mynewflags). Both of these functions return a copy of the fmtflags object in its state before the call to flags.


Implementing a custom manipulator set would be a bit more difficult, and requires the implementer to first decide how they wish to store and access those manipulators. Personally, I would have a preference for implementing another stream object inheriting from std::ios_base, possibly indirectly, and using it to encapsulate both a base stream (probably just one from the standard library, with this new class possibly templated on the stream type) and the additional manipulator flags. Anything else would require either a way of checking for the manipulator flags in an external variable, or remembering to pass the variable in with any printing function, which would put a damper of the use of operator<< for output. This mean you would need to make another member function for polling your custom flags, but really that seems wise anyway.

jaggedSpire
  • 4,423
  • 2
  • 26
  • 52
  • Thanks for the quick answer. The ironic thing is that I was already using the flags function to save and restore state but had missed that I could also introspect with it. – Ken Clement Nov 23 '15 at 20:48