c++ - How to use boost::iostreams::null_sink as std::ostream -


i want make output verbose/non verbose based on flag given @ runtime. idea is, construct std::ostream dependent of flag, such in:

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

now i'm stuck constructing std::ostream such boost streambuffer. how this?

using standard library

just reset rdbuf:

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

otherwise, use stream:

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

see 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 insist:

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

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -