Standard no-op output stream

后端 未结 6 1834
余生分开走
余生分开走 2020-11-29 03:25

Is there a way to create an ostream instance which basically doesn\'t do anything ?

For example :

std::ostream dummyStream(...);
dummyStream <<         


        
6条回答
  •  心在旅途
    2020-11-29 04:04

    For runtime-controllable redirection of log messages, a self-contained solution combining the ideas of john and Sjoerd:

    class DebugStream {
    private:
        class NullStream : public std::ostream {
        private:
            class NullBuffer : public std::streambuf {
            public:
                int overflow(int c) override { return c; }
            } buffer_;
        public:
            NullStream() : std::ostream(&buffer_) {}
        } null_;
    
        std::ostream &output_;
        bool enabled_;
    
    public:
        DebugStream(std::ostream &output = std::cout) : output_(output), enabled_(false) {}
        void enable(const bool enable) { enabled_ = enable; }
    
        template  std::ostream& operator<<(const T &arg) {
            if (enabled_) return output_ << arg;
            else return null_ << arg;
        }
    };
    
    extern DebugStream debug_stream;
    #define TRACE_ENABLE(x) debug_stream.enable(x)
    #define TRACELN(x) debug_stream << x << std::endl
    #define TRACE(x) debug_stream << x
    

    Then you can do stuff like:

    TRACELN("The value of x is " << x " and the value of y is " << y);
    

    It would also be easy to just remove the trace statements from a release version completely with #define the trace macros to empty statements.

    You still need to define debug_stream somewhere global, though.

提交回复
热议问题