简体   繁体   English

扩展C ++ ostream

[英]Extending C++ ostream

I'm trying to learn more about the workings of the C++ I/O stream library by extending std::streambuf . 我试图通过扩展std::streambuf来了解有关C ++ I / O流库的更多信息。 As a learning experiment, my goal is to simply create a custom stream which directs all output to std::cerr . 作为一个学习实验,我的目标是简单地创建一个自定义流,该流将所有输出定向到std::cerr It seems simple enough: 看起来很简单:

#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";
}

This seems to work, since it prints Redirecting to cerr: TEST . 这似乎可行,因为它显示Redirecting to cerr: TEST The problem is that it doesn't work when a single character (as opposed to a string) is inserted into the stream via std::ostream::sputc . 问题是,当通过std::ostream::sputc单个字符 (而不是字符串)插入流中时,它不起作用 For example: 例如:

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
}

The problem I guess is that xsputn doesn't handle single character insertion. 我猜的问题是xsputn无法处理单个字符的插入。 (I guess sputc doesn't call xsputn internally?) But, looking over the list of virtual protected functions in std::streambuf , I don't see any function I'm supposed to override that handles single character insertion. (我猜sputc不会在内部调用xsputn吗?)但是,在std::streambuf查看虚拟受保护函数列表时 ,我看不到应该重写的处理单个字符插入的任何函数。

So, how can I accomplish this? 那么,我该怎么做呢?

Single-character output is handled by overflow . 单字符输出由overflow处理。 Here's how you might implement overflow in terms of xsputn if xsputn does the actual outputting: 如果xsputn进行实际输出,则可以按照xsputn来实现overflow

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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