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

北战南征 提交于 2019-12-05 10:16:24

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

Follow up: OK, here is the derived std::streambuf that implements required functionality:

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 just create a std::ostream and initialize with this buffer

std::ostream os(new listboxstreambuf(some_list_box_object));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!