我想在我的代码中公开流作为它们的标准等价物,以消除用户对boost::iostreams
的依赖。当然,希望有效地执行此操作,而无需在必要时创建副本。我想过将std::istream
的缓冲区设置为boost::iostream::stream<boost::iostreams::source>
使用的缓冲区,但是,这可能会导致所有权问题。如何将boost::iostream
转换为等效std::iostream
?特别boost::iostream::stream<boost::iostreams::source>
std::istream
.
无需转换:
住在科里鲁
#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 worldnbye world";
io::array_source source(buf, strlen(buf));
io::stream<io::array_source> is(source);
foo(is);
}
除此之外,我认为您不会遇到所有权问题,因为std::istream
在分配新的 rdbuf 时不会承担所有权:
- 为什么 std::istream 不对其 streambuf 拥有所有权?
因此,您也可以自由地执行以下操作:
住在科里鲁
std::istream wrap(is.rdbuf());
foo(wrap);
打印相同