【问题标题】:Using boost stream_buffer with std::ofstream将 boost stream_buffer 与 std::ofstream 一起使用
【发布时间】:2017-12-05 22:50:24
【问题描述】:

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?我已经实现了一个自定义接收设备,我可以用它来创建一个 boost 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 构造函数无法编译。任何可能的解决方法?

【问题讨论】:

  • 没有。没有解决方法。
  • @noxmetus 你会感到惊讶的。

标签: c++ boost stl ofstream ostream


【解决方案1】:

您可以做的是使用其默认构造函数创建一个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.

【讨论】:

  • 谢谢,这正是我想要的!
  • 最好的语法是“out.std::ostream::rdbuf(&mybuf)”,不带static_cast。然而。是笑话吗?你不能是认真的。或者你在这里没有看到问题,是吗?例如尝试回答这个问题:如果我写“std::ofstream ofs = std::move(out);”会发生什么。提示:std::basic_ofstream 存储 std::basic_filebuf 并直接访问它。
  • @noxmetus 哪些ofstream 函数直接访问缓冲区?
  • @noxmetus 这个语法从我脑海中溜走,谢谢提醒。
  • 这取决于实现:-O。但这没关系。通过您的破解,您将获得一个合同损坏的对象。在某些情况下它可能会起作用,但是像这样编程的家伙应该被毫不留情地解雇,除非它是 RCG 或实习生。
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 2011-09-14
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-04
相关资源
最近更新 更多