如何将boost :: iostreams :: null_sink用作std :: ostream [英] How to use boost::iostreams::null_sink as std::ostream

查看:126
本文介绍了如何将boost :: iostreams :: null_sink用作std :: ostream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Now I'm stuck with constructing a std::ostream from such a boost streambuffer. How would I do this?

推荐答案

使用标准库

只需重置rdbuf:

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

否则,只需使用流:

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

查看 在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 IOstreams

Using Boost Iostreams

You /can/ of course use Boost IOstreams if you insist:

请注意,根据评论,这绝对是更好的选择,因为流不会一直处于错误"状态.

Note, as per the comments, this is strictly better because the stream will not be in "error" state all the time.

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

这篇关于如何将boost :: iostreams :: null_sink用作std :: ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆