如何使用boost :: iostreams管道进入std :: cout

时间:2014-01-09 21:26:23

标签: c++ boost iostream boost-iostreams

我是boost::iostreams的新手,所以这可能是微不足道的:

假设namespace io = boost::iostreams;

这是有效的

io::filtering_ostream out(std::cout);
out << "some\nstring\n";

这是有效的

std::string result;
io::filtering_ostream out(io::counter() | io::back_inserter(result));
out << "some\nstring\n";

但这不会编译

io::filtering_ostream out(io::counter() | std::cout);
out << "some\nstring\n";

如何管道std::cout

3 个答案:

答案 0 :(得分:5)

boost::ref包裹std::cout为我工作:

io::filtering_ostream out(DummyOutputFilter() | boost::ref(std::cout));

有关详细信息,请参阅pipable docs中的note_1。

答案 1 :(得分:2)

为了完整起见,一个简单的“Sink wrapper”看起来像这样:

#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/pipeline.hpp>

template<typename Sink>
class sink_wrapper
    : public boost::iostreams::device<boost::iostreams::output, typename Sink::char_type> {
public:
    sink_wrapper(Sink & sink) : sink_(sink) {}

    std::streamsize write(const char_type * s, std::streamsize n) {
        sink_.write(s, n);
        return n;
    }

private:
    sink_wrapper & operator=(const sink_wrapper &);
    Sink & sink_;
};
BOOST_IOSTREAMS_PIPABLE(sink_wrapper, 1)

template<typename S> sink_wrapper<S> wrap_sink(S & s) { return sink_wrapper<S>(s); }

可以像这样使用:

boost::iostreams::filtering_ostream  out(filter | wrap_sink(std::cout));

答案 2 :(得分:1)

这不是你传递流的方式。您必须使用push

out.push(std::cout);