我想根据运行时给出的标志使我的输出详细/非详细。我的想法是,构建一个依赖于标志的 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
}
现在我坚持从这样一个 boost 流缓冲区构建一个 std::ostream。我该怎么做?
最佳答案
使用标准库
只需重置rdbuf
:
auto old_buffer = std::cout.rdbuf(nullptr);
否则,只需使用流:
std::ostream nullout(nullptr);
std::ostream& out = verbose? std::cout : nullout;
#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";
}
当运行./test.exe
时:
Running in verbose mode: false
当运行 ./test.exe --verbose
时:
Running in verbose mode: true
Hello world
使用 Boost Iostream
如果您坚持,您/当然可以/使用 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";
}
关于c++ - 如何将 boost::iostreams::null_sink 用作 std::ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141745/