我想根据运行时给出的标志使输出详细/非详细。我的想法是,构造一个依赖于标志的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
}
现在我不得不从这样的提升streambuffer构建一个std :: ostream。我该怎么做?
答案 0 :(得分:7)
只需重置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:
请注意,根据评论,这绝对更好,因为流不会出现在&#34;错误&#34;一直都在说。
<强> 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";
}