简体   繁体   中英

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

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?

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

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