简体   繁体   中英

Conditional output

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

看一下有关过滤后的流缓冲的这篇论文

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM