I've had multiple questions on the matter of streams and stuff, but after thinking for a bit, I've come to the conclusion that all I need is a custom flush type. I want my stream to flush when it gets a new line. It saves having to type out std::endl. Is it possible to implement this? I'm using an ostream with a custom stringbuf.
Asked
Active
Viewed 444 times
1
-
Pardon me, but why is typing `endl` a few times more difficult that writing a new stream from (almost) scratch ? – Alexandre C. Dec 11 '10 at 16:36
-
It's not as much as it is out of interest of it being possible and if so, how. – Jookia Dec 11 '10 at 16:37
1 Answers
1
I believe all it would take is overriding ostream::put(char)
, but don't quote me on that:
template <typename Ch>
class autoflush_ostream : public basic_ostream<Ch> {
public:
typedef basic_ostream<Ch> Base;
autoflush_ostream& put(Ch c);
};
template <typename Ch>
autoflush_ostream<Ch>& autoflush_ostream<Ch>::put(Ch c) {
Base::put(c);
if (c == "\n") {
flush();
}
return *this;
}
You might have to override every method and function that takes a character or sequence of characters that's defined in the STL. They would all basically do the same thing: call the method/function defined on the super class, check if a newline was just printed and flush if so.

outis
- 75,655
- 22
- 151
- 221
-
basic_ostream::put is not virtual, so the derived class's version won't be used unless the object's static type is autoflush_ostream (i.e. an autoflush_ostream object, reference, or pointer). In particular, this means `stream << '\n'` cannot call your put. – Fred Nurk Dec 11 '10 at 20:17
-