Search code examples
c++boostiostreamboost-iostreams

convert boost::iostream::stream<boost::iostreams::source> to std::istream


I would like to expose streams in my code as their standard equivalents to eliminate user dependency on boost::iostreams. Would like to do this efficiently of course without creating a copy if necessary. I thought about just setting the std::istream's buffer to the one being used by the boost::iostream::stream<boost::iostreams::source>, however, this could cause ownership problems. How do you convert boost::iostream to std::iostream equivalent? Particularly boost::iostream::stream<boost::iostreams::source> to std::istream.


Solution

  • No conversion is needed:

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

    Other than that I don't think you could have ownership issues, since std::istream doesn't assume ownership when assigned a new rdbuf:

    So, you're also free to do:

    Live On Coliru

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

    Printing the same