[英]Conditional output
I'd like to create a C++ ostream object that only outputs anything if a condition holds true, to use for debugging. 我想创建一个C ++ ostream对象,该对象仅在条件成立时才输出任何内容,以用于调试。 What would be the easiest way to do this?
最简单的方法是什么? I know that boost has classes that make this easy, but I'd like to know if there's a simple way to do it without boost.
我知道boost具有使这一点变得容易的类,但是我想知道是否有一种简单的方法可以在不进行Boost的情况下进行操作。 The documentation makes it seem like subclassing ostream::sentry would make this possible, but I can't find any source saying that's something that you can/should do.
该文档看起来像是将ostream :: sentry子类化将使之成为可能,但我找不到任何消息源表明您可以/应该这样做。
Don't subclass, it's easier to use a wrapper: 不要子类化,使用包装器会更容易:
class MaybeOstream
{
public:
MaybeOstream(std::ostream& stream_) : stream(stream_), bOutput(true) {}
void enable(bool bEnable) { bOutput = bEnable; }
template<typename T>
MaybeOstream& operator<< (T x)
{
if(bOutput)
stream << x;
return *this;
}
// Add other wrappers around ostream: operator void*, good(), fail(),
// eof(), etc., which just call through to the ostream
private:
std::ostream& stream;
bool bOutput;
}
看一下有关过滤后的流缓冲的这篇论文 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.