[英]Having a class that has a write function, how to I pass it to a function accepting std::ostream&
I have an instance of a class which implements a writing interface such as this one:我有一个 class 的实例,它实现了一个这样的写入接口:
struct Writer {
virtual size_t write(const char* buffer, size_t size, size_t offset) = 0;
};
I also have a function that takes the std::ostream&
as an argument and writes to it.我还有一个 function 将
std::ostream&
作为参数并写入它。 Like so:像这样:
void foo(std::ostream& os) {
os << "hello world"; // Say, I don't control this code
}
What is the simplest way to make foo
write into my instance of the Writer
interface?让
foo
写入我的Writer
接口实例的最简单方法是什么?
Bonus points for a Reader
interface and std::istream
. Reader
接口和std::istream
的奖励积分。
EDIT:编辑:
Maybe I should also mention, I must assume that foo
writes a huge amount of data to the std::ostream
, thus a solution where foo
first writes into std::stringstream
which I then write into the Writer
won't work.也许我还应该提到,我必须假设
foo
将大量数据写入std::ostream
,因此foo
首先写入std::stringstream
然后我写入Writer
的解决方案将不起作用。
Working using code from A custom ostream , I was able to write:使用来自A custom ostream 的代码,我能够编写:
#include <iostream>
#include <sstream>
struct Writer {
virtual size_t write(const char* buffer, size_t size, size_t offset) = 0;
};
Writer& getWriter();
void foo(std::ostream& os);
struct WriteToWriter : public std::stringbuf {
Writer& w;
std::size_t offset{0};
WriteToWriter(Writer& w) : w(w) {}
virtual std::streamsize xsputn(const char_type* s, std::streamsize n) override {
const size_t r = w.write(s, n, offset);
offset += r;
return r;
}
virtual int_type overflow(int_type c) override {
if (c == EOF) return EOF;
char tmp = c;
const size_t r = w.write(&tmp, 1, offset);
offset += r;
return r == 1 ? c : EOF ;
}
};
int main()
{
WriteToWriter wtw(getWriter());
std::ostream out(&wtw);
foo(out);
}
that looks like it should write directly to Writer::write
看起来它应该直接
Writer::write
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.