std :: endl的过载处理? [英] Overload handling of std::endl?
问题描述
我想定义一个类 MyStream
,以便:
I want to define a class MyStream
so that:
MyStream myStream;
myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl;
提供输出
[blah]123
[blah]56
[blah]78
$ b b
基本上,我想在前面插入一个[blah],然后在每个不终止 std :: endl
之后插入?
这里的困难不是逻辑管理,而是检测和重载 std :: endl
的处理。是否有优雅的方式来做这个?
The difficulty here is NOT the logic management, but detecting and overloading the handling of std::endl
. Is there an elegant way to do this?
谢谢!
编辑:我不需要建议逻辑管理。我需要知道如何检测/重载 std :: endl
的打印。
I don't need advice on logic management. I need to know how to detect/overload printing of std::endl
.
推荐答案
您需要做的是编写自己的流缓冲区:
当流缓冲区被刷新时,输出前缀字符和流的内容。
What you need to do is write your own stream buffer:
When the stream buffer is flushed you output you prefix characters and the content of the stream.
以下工作原因是因为std :: endl导致了以下操作。
The following works because std::endl causes the following.
1)向流中添加\\\
。
2)调用流上的flush()
2a)调用流缓冲区上的pubsync()。
2b)调用虚方法sync()
2c)覆盖此虚拟方法以完成您想要的工作。
1) Add '\n' to the stream.
2) Calls flush() on the stream
2a) This calls pubsync() on the stream buffer.
2b) This calls the virtual method sync()
2c) Override this virtual method to do the work you want.
#include <iostream>
#include <sstream>
class MyStream: public std::ostream
{
// Write a stream buffer that prefixes each line with Plop
class MyStreamBuf: public std::stringbuf
{
std::ostream& output;
public:
MyStreamBuf(std::ostream& str)
:output(str)
{}
// When we sync the stream with the output.
// 1) Output Plop then the buffer
// 2) Reset the buffer
// 3) flush the actual output stream we are using.
virtual int sync ( )
{
output << "[blah]" << str();
str("");
output.flush();
return 0;
}
};
// My Stream just uses a version of my special buffer
MyStreamBuf buffer;
public:
MyStream(std::ostream& str)
:std::ostream(&buffer)
,buffer(str)
{
}
};
int main()
{
MyStream myStream(std::cout);
myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl;
}
> ./a.out
[blah]123
[blah]56
[blah]78
>
这篇关于std :: endl的过载处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!