开发者

Conditional output

开发者 https://www.devze.com 2023-04-12 02:43 出处:网络
I\'d like to create a C++ ostream object that only outputs anything if a condition holds true, to use for debugging. What would be the easiest way to do this? I know that boost has classes that make t

I'd like to create a C++ ostream object that only outputs anything if a condition holds true, to use for debugging. 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. 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/shou开发者_JAVA技巧ld do.


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;
}


Take a look at this paper on filtered streambufs.

0

精彩评论

暂无评论...
验证码 换一张
取 消