多输出带前缀输出流

http://stackoverflow.com/questions/2212776/overload-handling-of-stdendl 写道
#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
>
 

略微修改后:

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

 

 

 

你可能感兴趣的:(输出流)