[英]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,例如:
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. 现在我不得不从这样的提升streambuffer构建一个std :: ostream。 How would I do this?
我该怎么做?
Just reset the rdbuf
: 只需重置
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 看到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
: 运行
./test.exe
:
Running in verbose mode: false
When run ./test.exe --verbose
: 运行时
./test.exe --verbose
:
Running in verbose mode: true
Hello world
You /can/ of course use Boost IOstreams if you insist: 如果您坚持,您/可以/当然使用Boost IOstreams:
Note, as per the comments, this is strictly better because the stream will not be in "error" state all the time.
请注意,根据评论,这是非常好的,因为流不会一直处于“错误”状态。
#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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.