扩展C ++ ostream [英] Extending C++ ostream
问题描述
我正在尝试通过扩展std::streambuf
来了解有关C ++ I/O流库的更多信息.作为一个学习实验,我的目标是简单地创建一个自定义流,将所有输出定向到std::cerr
.看起来很简单:
I'm trying to learn more about the workings of the C++ I/O stream library by extending std::streambuf
. As a learning experiment, my goal is to simply create a custom stream which directs all output to 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";
}
这似乎可行,因为它会打印Redirecting to cerr: TEST
.问题在于,当通过std::ostream::sputc
将单个字符(而不是字符串)插入流中时,不起作用.例如:
This seems to work, since it prints 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
. 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
}
我想的问题是xsputn
无法处理单个字符的插入. (我想sputc
不会在内部调用xsputn
?)但是,请查看 std::streambuf
中的虚拟受保护功能列表,我看不到应该覆盖任何处理单个字符插入的功能.
The problem I guess is that xsputn
doesn't handle single character insertion. (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.
那么,我该怎么做呢?
推荐答案
单字符输出由overflow
处理.如果xsputn
进行实际输出,则可以按照xsputn
的方式实现overflow
:
Single-character output is handled by overflow
. Here's how you might implement overflow
in terms of xsputn
if xsputn
does the actual outputting:
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();
}
}
这篇关于扩展C ++ ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!