---
title: "多输出带前缀输出流 "
author: "chenqi210"
date: "2012-10-29T11:37:12Z"
tags: []
categories: ["开源软件"]
slug: "untitled"
draft: false
lastmod: "2012-10-29T11:41:18Z"
id: 1707198
url: "https://chenqi210.iteye.com/blog/1707198"
---

http://stackoverflow.com/questions/2212776/overload-handling-of-stdendl 写道

#include &lt;iostream&gt;  
#include &lt;sstream&gt;

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 &lt;&lt; "\[blah]" &lt;&lt; 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 &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3 &lt;&lt; std::endl &lt;&lt; 5 &lt;&lt; 6 &lt;&lt; std::endl &lt;&lt; 7 &lt;&lt; 8 &lt;&lt; std::endl;  
}

&gt; ./a.out  
\[blah]123  
\[blah]56  
\[blah]78  
&gt;

 

略微修改后：

```
class test2_stream : public ostream
{
	class test2_streambuf : public stringbuf
	{
		public:
			test2_streambuf(test2_stream &parent)
				:m_parent(parent)
			{}

			virtual int sync()
			{
				string t = DateTime::now().toString();
				string s = str();
				for(vector<ostream*>::iterator it = m_parent.m_outs.begin();
						it != m_parent.m_outs.end();
						++it) {
					(**it) << '[' << t << "]: " << s;
					(**it).flush();
				}
				seekoff(0, ios::beg);
				return 0;
			}
		private:
			test2_stream &m_parent;
	};

	public:
		test2_stream()
			:ostream(&m_buf),
			m_buf(*this)
		{}
		test2_stream& attach(ostream& os)
		{
			m_outs.push_back(&os);
			return *this;
		}
		test2_stream& detach(ostream& os)
		{
			m_outs.erase(std::remove(m_outs.begin(), m_outs.end(), &os), m_outs.end());
			return *this;
		}
	private:
		vector<ostream*> m_outs;
		test2_streambuf m_buf;
};
```