许多格式化输出操作符(operator<<
)直接写入基础流缓冲区。为了以一般方式完成此任务,您需要做的是从std :: basic_streambuf派生一个类,它将所有数据转发到另一个std :: basic_streambuf,然后可选地创建一个最小std :: basic_ostream实现来使用您的流缓冲更容易。
虽然我不会说这很容易,但它是唯一能够影响所有流类型的方法。
这里是转发到另一个流缓冲区(和执行一些毫无意义的转变只是证明你能够做什么)的最小流缓冲区的例子,并伴随流:
#include <iostream>
#include <streambuf>
template<typename CharType, typename Traits = std::char_traits<CharType> >
class ForwardingStreamBuf : public std::basic_streambuf<CharType, Traits>
{
public:
typedef Traits traits_type;
typedef typename traits_type::int_type int_type;
typedef typename traits_type::pos_type pos_type;
typedef typename traits_type::off_type off_type;
ForwardingStreamBuf(std::basic_streambuf<CharType, Traits> *baseStreamBuf)
: _baseStreamBuf(baseStreamBuf)
{
}
protected:
virtual int_type overflow(int_type c = traits_type::eof())
{
if(_baseStreamBuf == NULL)
return traits_type::eof();
if(traits_type::eq_int_type(c, traits_type::eof()))
return traits_type::not_eof(c);
else
{
CharType ch = traits_type::to_char_type(c);
if(ch >= 'A' && ch <= 'z')
ch++; // Do some meaningless transformation
return _baseStreamBuf->sputc(ch);
}
}
virtual int sync()
{
if(_baseStreamBuf == NULL)
return -1;
else
return _baseStreamBuf->pubsync();
}
private:
std::basic_streambuf<CharType, Traits> *_baseStreamBuf;
};
template<typename CharType, typename Traits = std::char_traits<CharType> >
class ForwardingStream : public std::basic_ostream<CharType, Traits>
{
public:
ForwardingStream(std::basic_ostream<CharType, Traits> &stream)
: std::basic_ostream<CharType, Traits>(NULL), _buffer(stream.rdbuf())
{
this->init(&_buffer);
}
ForwardingStreamBuf<CharType, Traits>* rdbuf() const
{
return &_buffer;
}
private:
ForwardingStreamBuf<CharType, Traits> _buffer;
};
这可以用于很简单:
int main()
{
ForwardingStream<char> test(std::cout);
test << "Foo" << std::endl;
}
哪个会输出Gpp
。我希望这可以帮助你。
没有必要。只需使用`iostream`,而不是`fstream`。 – 2011-06-17 12:06:06