How to write custom manipulators for a streaming self-written class

How to write custom stream manipulators in C ++ that control the stream recording format of a sampling class?

In particular, how could I write simple verbose and terse to control the output volume of a stream?

My environment is GCC, version 4.5.1 and higher.

Example:

 class A { ... }; A a; // definition of manipulators verbose and terse cout << verbose << a << endl; // outputs a verbosely cout << terse << a << endl; // outputs a tersely 

PS: The following is just a side question, feel free to ignore it: is it portable to extend to manipulators that take arguments? Josuttis writes in the "C ++ Standard Library" at the end of section 13.6.1 that manipulating manipulators using an argument is implementation dependent. It's true?

+8
c ++ iostream
source share
1 answer

I see no reason for their dependent implementation.

This is what I use for the actual manipulator, I create a function that returns an instance of the next helper. If you need to save data, just save it inside the helper, some global variable, singleton, etc.

  /// One argument manipulators helper template < typename ParType > class OneArgManip { ParType par; std::ostream& (*impl)(std::ostream&, const ParType&); public: OneArgManip(std::ostream& (*code)(std::ostream&, const ParType&), ParType p) : par(p), impl(code) {} // calls the implementation void operator()(std::ostream& stream) const { impl(stream,par); } // a wrapper that allows us to use the manipulator directly friend std::ostream& operator << (std::ostream& stream, const OneArgManip<ParType>& manip) { manip(stream); return stream; } }; 

An example of a manipulator based on this:

 OneArgManip<unsigned> cursorMoveUp(unsigned c) { return OneArgManip<unsigned>(cursorMoveUpI,c); } std::ostream& cursorMoveUpI(std::ostream& stream, const unsigned& c) { stream << "\033[" << c << "A"; return stream; } 

For some explanation:

  • u use a manipulator that returns a new helper instance associated with the helper thread implementation
  • tries to process an assistant that causes an overload << on the secondary server
  • which calls the statement () in the helper
  • which calls the real implementation of the helper with the parameter passed from the original manipulator call

If you want, I can send 2 param helpers and 3 param. The principle is the same, though.

+2
source share

All Articles