How to get std :: basic_ostream from C ++ and make the << operator virtual?

I am writing a class that displays various messages. I want to make this class generic and platform independent, so I'm thinking of passing a basic_ostream link , and it can upload all the messages to the stream. By doing this, if the class is used in a console program, I can pass std :: cout to it and display it in the console window.

Or I could pass the output and redirect the message to some components of the user interface, for example. Listbox The only problem is data insertion is operator <<not a virtual function. If I pass a reference to a derived class, only the basic_ostream <statement will be called.

Is there any workaround for this?

+5
source share
1 answer

Nan Zhang's own answer, originally published as part of the question:

Followup: OK, here is the derived std :: streambuf that implements the required functions:

class listboxstreambuf : public std::streambuf { 
public:
    explicit listboxstreambuf(CHScrollListBox &box, std::size_t buff_sz = 256) :
            Scrollbox_(box), buffer_(buff_sz+1) {
        char *base = &buffer_.front();
        //set putbase pointer and endput pointer
        setp(base, base + buff_sz); 
    }

protected:
    bool Output2ListBox() {
        std::ptrdiff_t n = pptr() - pbase();
        std::string temp;
        temp.assign(pbase(), n);
        pbump(-n);
        int i = Scrollbox_.AddString(temp.c_str());
        Scrollbox_.SetTopIndex(i);
        return true;
    }

private:
    int sync() {
        return Output2ListBox()? 0:-1;
    }

    //copying not allowed.
    listboxstreambuf(const listboxstreambuf &);
    listboxstreambuf &operator=(const listboxstreambuf &);

    CHScrollListBox &Scrollbox_;
    std::vector<char> buffer_;
};

To use this class, simply create std :: ostream and initialize using this buffer

std::ostream os(new listboxstreambuf(some_list_box_object));
+1

All Articles