我想定义一个类MyStream
以便:
MyStream myStream;
myStream << 1 << 2 << 3 << std::endl << 5 << 6 << std::endl << 7 << 8 << std::endl;
给出输出
[blah]123
[blah]56
[blah]78
基本上,我想在前面插入一个“[blah]”,然后在每个之后插入非终止 std::endl
?
这里的困难不是逻辑管理,而是检测和重载处理std::endl
。有没有一种优雅的方法来做到这一点?
Thanks!
编辑:我不需要有关逻辑管理的建议。我需要知道如何检测/过载打印std::endl
.
您需要做的是编写自己的流缓冲区:刷新流缓冲区时,您将输出前缀字符和流的内容。
以下工作是因为std::endl
导致以下情况。
-
Add '\n'
到溪流。
-
Calls flush()
在流中
-
这调用pubsync()
在流缓冲区上。
- 这调用了虚拟方法
sync()
- 重写此虚拟方法来完成您想要的工作。
#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)
{}
~MyStreamBuf() {
if (pbase() != pptr()) {
putOutput();
}
}
// 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() {
putOutput();
return 0;
}
void putOutput() {
// Called by destructor.
// destructor can not call virtual methods.
output << "[blah]" << str();
str("");
output.flush();
}
};
// 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
>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)