【问题标题】:How to pipe into std::cout with boost::iostreams如何使用 boost::iostreams 管道进入 std::cout
【发布时间】:2014-01-28 16:04:28
【问题描述】:

我是 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

【问题讨论】:

    标签: c++ boost iostream boost-iostreams


    【解决方案1】:

    boost::ref 包裹std::cout 对我有用:

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

    详情请参阅pipable docs 中的 note_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));
      

      【讨论】:

        【解决方案3】:

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

        out.push(std::cout);
        

        【讨论】:

        • 那么为什么back_inserter 有效?有没有“管道”的方式来做到这一点?
        • @3noch back_inserter 和它有什么关系?那不是流,那是设备……
        • 不能把std::stream转成设备吗?我期待像 make_device(std::cout) 这样的东西。
        • @3noch 我的意思是它不代表设备概念。您实际上无法创建这样的设备。
        • @3noch 您是否正在寻找一种“管道”方式来简化您的代码?只是好奇。 :)
        猜你喜欢
        • 1970-01-01
        • 2010-10-14
        • 2017-07-02
        • 2017-05-23
        • 2020-07-19
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        • 1970-01-01
        相关资源
        最近更新 更多