How to pipe into std::cout with boost::iostreams

孤者浪人 提交于 2020-05-23 09:52:49

问题


I am new to boost::iostreams so this might be trivial:

Assuming namespace io = boost::iostreams;

this works

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

and this works

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

yet this does not compile

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

How do you pipe into std::cout?


回答1:


Wrapping std::cout with boost::ref worked for me:

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

See note_1 in pipable docs for details.




回答2:


For the sake of completeness, a simple "Sink wrapper" looks like this:

#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); }

And can be used like this:

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



回答3:


That's not the way you pass the stream. You have to use push:

out.push(std::cout);


来源:https://stackoverflow.com/questions/21031502/how-to-pipe-into-stdcout-with-boostiostreams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!