使用 boost stream_buffer 和 std::ofstream

Using boost stream_buffer with std::ofstream

boost iostreams tutorial 我读到可以将 boost stream_buffer 与 std::ostream 一起使用,如教程中所示:

#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    io::stream_buffer<io::file_sink> buf("log.txt");
    std::ostream                     out(&buf);
    // out writes to log.txt
}

我们如何使用 boost stream_buffer 来创建 std::ofstream?我已经实现了一个自定义接收器设备,我可以用它来创建一个提升 stream_buffer。使用流缓冲区,我可以创建 std::ostream,但不能创建 std::ofstream.

// ...
io::stream_buffer<my_custom_file_sink> mybuf("myfile.txt"); // Creating stream_buffer works
std::ostream out(&mybuf); // Here I would like to use std::ofstream
// ...

我需要它,因为我正在使用的另一个库需要 std::ofstream&。但不幸的是,将 boost stream_buffer 传递给 std::ofstream 构造函数无法编译。任何可能的解决方法?

您可以做的是使用其默认构造函数创建一个 std::ofstream,然后将您的缓冲区分配给它:

io::stream_buffer<my_custom_file_sink> mybuf("myfile.txt");

std::ofstream out;
out.std::ostream::rdbuf(&mybuf); // Call the base class version.