![](/img/trans.png)
[英]How to use boost::iostreams::null_sink as std::ostream
[英]How to pipe into std::cout with 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
?
用boost :: ref包裝std::cout
對我std::cout
:
io::filtering_ostream out(DummyOutputFilter() | boost::ref(std::cout));
為了完整起見,一個簡單的“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));
那不是你傳遞流的方式。 你必須使用push
:
out.push(std::cout);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.