如何使用boost :: iostreams :: null_sink作为std :: ostream

时间:2015-10-15 06:51:49

标签: c++ boost

我想根据运行时给出的标志使输出详细/非详细。我的想法是,构造一个依赖于标志的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。我该怎么做?

1 个答案:

答案 0 :(得分:7)

使用标准库

只需重置rdbuf

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

否则,只需使用流:

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

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

运行./test.exe时:

Running in verbose mode: false

运行./test.exe --verbose时:

Running in verbose mode: true
Hello world

使用Boost Iostreams

如果你坚持的话,你/当然可以使用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";
}
相关问题