将 boost::iostream::stream<boost::iostreams::source> 转换为 std::istream
convert boost::iostream::stream<boost::iostreams::source> to std::istream
我想在我的代码中公开流作为标准等价物,以消除用户对 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 world\nbye world";
io::array_source source(buf, strlen(buf));
io::stream<io::array_source> is(source);
foo(is);
}
除此之外,我认为您不会有所有权问题,因为 std::istream
在分配新的 rdbuf 时不承担所有权:
- Why doesn't std::istream assume ownership over its streambuf?
所以,你也可以自由地做:
std::istream wrap(is.rdbuf());
foo(wrap);
打印相同
我想在我的代码中公开流作为标准等价物,以消除用户对 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 world\nbye world";
io::array_source source(buf, strlen(buf));
io::stream<io::array_source> is(source);
foo(is);
}
除此之外,我认为您不会有所有权问题,因为 std::istream
在分配新的 rdbuf 时不承担所有权:
- Why doesn't std::istream assume ownership over its streambuf?
所以,你也可以自由地做:
std::istream wrap(is.rdbuf());
foo(wrap);
打印相同