标准流适配器

Adapter for std streams

我的项目中有一个抽象class,它的衍生物用于input/output到不同的位置。 它有虚拟方法 readwrite.

virtual unsigned read(void *buf, unsigned len) = 0;
virtual void write(const void *buf, unsigned len) = 0;

我需要一种在 std 流(std::istream 和 std::ostream)和这个 class 之间的适配器 来重定向 input/output 这些方法。

因此,例如,如果

mystream << "some output";

被调用,会调用write方法。

我想我应该重载 std::istreamstd::ostreamstd::streambuf ,但不确定是哪种方法。

实现这个的更好方法是什么?

我是std::stringstream的粉丝,也许你的class可以利用它。

std::stringstream ss;

ss << "some output";

从中调用的东西写成:

write(ss.str().c_str(),  ss.str().size());

您将不得不弄清楚如何连接两者,但这具有提供所有流 io 的优势。

另一方面,直接实现运算符<<和>>也不是太难。

I guess i should overload std::istream and std::ostream or std::streambuf, but not sure which methods.

首先从您需要的方法开始,然后在确定需求时添加功能。

您可能想看看 boost iostreams library。它提供了一个框架,可以更轻松地使用自定义源和接收器(输入和输出设备)定义 iostream。

有很多简单但没有灵活的方法。这些解决方案中的大多数不会利用 istreamostream。例如,重载 << 运算符是一种方法。缺点是您必须为所有常用类型和所有标准操纵器等实现此运算符。可能会成为很大的负担。

这很可悲,因为关于 istreamostream 的整件事只是 parseformat不做输入或输出。 I/O责任交给了streambuf。您的任务需要 streambuf 的自定义实现,它使用您的 readwrite 方法。

讨论对于像 Whosebug 答案这样的小格式来说太长了,但您可以在以下参考资料中找到很好的指示。

参考资料

备注

根据建议,使用 boost.iostreams 可能很合适,但我还不够了解。