gpt4 book ai didi

C++ 装饰 basic_iostream 类

转载 作者:可可西里 更新时间:2023-11-01 04:24:05 28 4
gpt4 key购买 nike

我想做一些类似下面代码所示的事情:

class foo
{
private:
std::fstream* m_stream;

public:
foo(std::fstream* stream) : m_stream(stream) { }

foo& write(char const* s, std::streamsize count)
{
if (/*condition*/)
{
m_stream->write(s, count);
}
else
{
// ...
}

return *this;
}

foo& read(char* s, std::streamsize count)
{
if (/*condition*/)
{
m_stream->read(s, count);
}
else
{
// ...
}

return *this;
}
};

我需要为所有类似的方法添加相同的行为(例如 put)。这不应仅应用于文件流,而是应用于所有其他流类。有什么简单的方法可以实现这些功能吗?

最佳答案

许多格式化输出运算符 ( 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 .希望对您有所帮助。

关于C++ 装饰 basic_iostream 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6384860/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com