Intercepting ostream between fields

Second try.

Is there a way in a class derived from ostream to intercept control between output operations to ostream.

I've considered:
1) Overloading every output operator in ostream. Defeats the intent of extensibility. I'd rather not rewrite ostream.
2) Implementing a sentry class. Does not seem to be possible to overload ostream's sentry. A sentry in my class gets control for output operators implemented in my class, but does not get control for output operators implemented in ostream.
3) opfx - Deprecated. Has been replaced by sentry.

Any ideas?
What are you hoping to accomplish, exactly?

Do you really want to intercept every output operation to every ostream, ofstream and ostringstream, even those used for simple conversion operations in libraries?

Could you replace the streambuf of selected streams to intercept the output?
Thanks for your response.

What I'm trying to accomplish is to perform some processing each time an output operator is called.
This would only be on instances of the derived class.

A very simple example would be to insert a field seperator between each field written to the derived class.
For example, a program is outputing a series of data items to an arbitrary ostream.
os << itema << itemb << endl;
The desired result would be:
itema | itemb |
where the "|" is inserted between each output operation.
I don't want to change the application, other than to use the class derived from osrream.

I had thought about overloading streambuf as you suggested.
In streambuf, neither sputc or sputn is virtual. However, the documentation states sputn calls xsputn which is virtual, so xsputn can be overloaded. This is promising, however it raises some questions.

a) sputc merely appends each charater to the buffer. Presumably, xsputn is called when the buffer is full since this appears to be the only way to return control back to ostream to do a physical write.

b) It does not appear that ostream's output operators are synchronized via calls to xsputn. i.e. I'm assuming here that ostream's output operators use a mix of sputc/sputn and that an output operator (such as << "literal") might call sputn, while other operators (<< 'Q') probably call sputc and don't force a call to xsputn.



Don't waste your time getting that low-level. The Boost Iostream library provides a filtering_ostream class that makes doing this a breeze.
Thanks for the pointer to the Boost Iostream library.
Topic archived. No new replies allowed.