5

我正在尝试通过扩展std::streambuf. 作为一个学习实验,我的目标是简单地创建一个自定义流,将所有输出定向到std::cerr. 看起来很简单:

#include <iostream>
using namespace std;

class my_ostreambuf : public std::streambuf
{
    public:

    protected:

    std::streamsize xsputn(const char * s, std::streamsize n)
    {
        std::cerr << "Redirecting to cerr: " << s << std::endl;
        return n;
    }

};

int main()
{
    my_ostreambuf buf;
    std::ostream os(&buf);
    os << "TEST";
}

这似乎有效,因为它打印Redirecting to cerr: TEST. 问题是当单个字符(而不是字符串)通过. 例如:std::ostream::sputc

int main()
{
    my_ostreambuf buf;
    std::ostream os(&buf);
    os << "ABC"; // works
    std::string s("TEST");
    std::copy(s.begin(), s.end(), std::ostreambuf_iterator<char>(os)); // DOESN'T WORK
}

我猜的问题是它xsputn不处理单个字符插入。(我想sputc不会在xsputn内部调用?)但是,查看中的虚拟受保护函数列表std::streambuf我看不到任何我应该重写的处理单个字符插入的函数。

那么,我该如何实现呢?

4

1 回答 1

5

单字符输出由overflow. 以下是根据实际输出是否可以实现overflow的方式:xsputnxsputn

int_type overflow(int_type c = traits_type::eof())
{
    if (c == traits_type::eof())
        return traits_type::eof();
    else
    {
        char_type ch = traits_type::to_char_type(c);
        return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
    }
}
于 2012-06-06T20:33:11.160 回答