简体   繁体   中英

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:

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. 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?

Bonus points for a Reader interface and 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.

Working using code from A custom ostream , I was able to write:

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM