Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use boost::iostreams::null_sink as std::ostream

Tags:

c++

boost

I want to make my output verbose/non verbose based on a flag given at runtime. My idea is, to construct a std::ostream dependent of the flag, such as in:

std::ostream out;
if (verbose) {
    out = std::cout
else {
    // Redirect stdout to null by using boost's null_sink.
    boost::iostreams::stream_buffer<boost::iostreams::null_sink> null_out{boost::iostreams::null_sink()};

    // Somehow construct a std::ostream from nullout
}

Now I'm stuck with constructing a std::ostream from such a boost streambuffer. How would I do this?

like image 796
panmari Avatar asked Oct 15 '15 06:10

panmari


1 Answers

Using Standard Library

Just reset the rdbuf:

auto old_buffer = std::cout.rdbuf(nullptr);

Otherwise, just use a stream:

std::ostream nullout(nullptr);
std::ostream& out = verbose? std::cout : nullout;

See it Live On Coliru

#include <iostream>

int main(int argc, char**) {
    bool verbose = argc>1;

    std::cout << "Running in verbose mode: " << std::boolalpha << verbose << "\n";

    std::ostream nullout(nullptr);
    std::ostream& out = verbose? std::cout : nullout;

    out << "Hello world\n";
}

When run ./test.exe:

Running in verbose mode: false

When run ./test.exe --verbose:

Running in verbose mode: true
Hello world

Using Boost Iostreams

You /can/ of course use Boost IOstreams if you insist:

Note, as per the comments, this is strictly better because the stream will not be in "error" state all the time.

Live On Coliru

#include <iostream>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/stream.hpp>

int main(int argc, char**) {
    bool verbose = argc>1;

    std::cout << "Running in verbose mode: " << std::boolalpha << verbose << "\n";

    boost::iostreams::stream<boost::iostreams::null_sink> nullout { boost::iostreams::null_sink{} };
    std::ostream& out = verbose? std::cout : nullout;

    out << "Hello world\n";
}
like image 111
sehe Avatar answered Nov 10 '22 03:11

sehe