Custom stream flush type
I've had multiple questions on the matter of streams and stuff, but after thinking 开发者_C百科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.
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.
精彩评论