我有很多关于流和东西的问题,但经过一番思考后,我得出的结论是我需要的只是一个自定义刷新类型。我希望我的流在换行时刷新。它省去了输入 std::endl 的麻烦。有可能实现吗?我正在使用带有自定义 stringbuf 的 ostream。
最佳答案
我相信它只需要覆盖 ostream::put(char)
,但不要引用我的话:
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;
}
您可能必须重写每个采用 STL 中定义的字符或字符序列的方法和函数。他们基本上都会做同样的事情:调用父类(super class)上定义的方法/函数,检查是否打印了换行符,如果是则刷新。
关于c++ - 自定义流冲洗类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4417682/