Search code examples
c++nullstreamoutput

is there a null stream? optional printing


I use functions like

void doStuff(type thing, bool print = false, std::ostream& S = std::cout)
{
    thing++;
    if(print)
        S << "new thing: " << thing << '\n';
}

so that I can use the same function and decide on call if I want it to print documentation of what is happening and if I wish I can print that on seperate streams -I don't know if I can even do that with std::ostream-

I now believe that it will be better to do

void doStuff(type thing, std::ostream& S = NULL)
{
    thing++;
    if(S)
        S << "new thing: " << thing << '\n';
}

but that doesn't work as std::ostream doesn't accept NULL

questions:
-is there some kind of constant of the stream type that stops the if condition?
-can I use a different type of stream that is more flexible to accept streams like string streams and file streams?
-is there a better way to handle flexible documentation?


Solution

  • Writing own streams is not difficult and can be found in good books.

    I created a "NULL" stream class for you.

    Please see the very simple example below.

    #include <iostream>
    
    // This is a stream which does not output anything
    class NullStream : public std::ostream
    {
        // streambuffer doing nothing
        class NullBuffer : public std::streambuf
        {
        public:
            int overflow(int c) noexcept override { return c; }
        } nullBuffer;
    
    public:
    #pragma warning(suppress: 26455)
        NullStream() : std::ostream(&nullBuffer) {}
        NullStream(const NullStream&) = delete;
        NullStream& operator=(const NullStream&) = delete;
    };
    
    
    // Define a global null stream
    NullStream nout;
    
    void doStuff(int& i, std::ostream& stream = nout)
    {
        i++;
        stream << i << '\n';
    }
    
    int main() {
    
        int i{};
        doStuff(i, std::cout);
        doStuff(i, std::cout);
        doStuff(i, std::cout);
        doStuff(i);
        doStuff(i);
        doStuff(i);
        doStuff(i, std::cout);
    }