【问题标题】:convert boost::iostream::stream<boost::iostreams::source> to std::istream将 boost::iostream::stream<boost::iostreams::source> 转换为 std::istream
【发布时间】:2017-07-02 04:28:05
【问题描述】:

我想在我的代码中公开流作为它们的标准等效项,以消除用户对boost::iostreams 的依赖。 如果有必要,当然希望在不创建副本的情况下有效地做到这一点。我考虑将std::istream 的缓冲区设置为boost::iostream::stream&lt;boost::iostreams::source&gt; 使用的缓冲区,但是,这可能会导致所有权问题。 你如何将boost::iostream 转换为std::iostream 等价物? 特别是boost::iostream::stream&lt;boost::iostreams::source&gt;std::istream

【问题讨论】:

    标签: c++ boost iostream boost-iostreams


    【解决方案1】:

    无需转换:

    Live On Coliru

    #include <iostream>
    #include <boost/iostreams/stream.hpp>
    #include <boost/iostreams/device/array.hpp>
    
    namespace io = boost::iostreams;
    
    void foo(std::istream& is) {
        std::string line;
        while (getline(is, line)) {
            std::cout << " * '" << line << "'\n";
        }
    }
    
    int main() {
        char buf[] = "hello world\nbye world";
        io::array_source source(buf, strlen(buf));
        io::stream<io::array_source> is(source);
    
        foo(is);
    }
    

    除此之外,我认为您不会有所有权问题,因为std::istream 在分配新的 rdbuf 时不会承担所有权:

    所以,你也可以这样做:

    Live On Coliru

    std::istream wrap(is.rdbuf());
    foo(wrap);
    

    打印一样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2011-03-12
      • 2010-12-29
      • 2016-05-14
      • 2017-05-21
      • 2012-06-25
      • 2014-03-27
      相关资源
      最近更新 更多