我想到了 C++ 中的一个小调试内联函数:
void inline debug( int debug_level, ostream& out ) {
if ( debug_level <= verbosity ) {
out.flush();
}
else {
ostream tmp;
tmp << out;
}
}
这是我想如何使用它的示例:
_debug( 7, cout << "Something something" << someint << endl );
但是它没有按我计划的方式工作——我希望它仅在详细级别高于或等于传递给函数的调试级别时才打印消息,但似乎无论调试级别如何,它每次都会打印,所以数据保留在 cout 缓冲区中。到目前为止,我认为这个函数不是我最近想到的最好的主意,但我仍然想知道是否有办法清除与 cout、cerr 等相关的缓冲区。是否有可能使这种函数正常工作?
最佳答案
要么使用如上所示的宏,要么像这样:
struct nullstream : ostream {
nullstream() : ostream(0) { }
};
ostream& dout(int debug_level, ostream& out = cerr) {
static nullstream dummy;
return debug_level <= verbosity ? dummy : out;
}
// …
dout(level) << "foo" << endl;
dout(level, cout) << "IMPORTANT" << endl;
(使用endl
也会触发flush,无需手动flush!)
关于C++ - 将 std::ostream 传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2191610/