创造一个ostream [英] creating an ostream
问题描述
我出于教育原因尝试创建一个c ++ ostream。我的测试将创建一个ostream,其行为像一个流,除了而不是写入一个文件,它将写入一个deque或向量容器。
I am trying to create a c++ ostream for educational reasons. My test will be creating an ostream that acts like a ofstream would except instead of writing to a file it would write to a deque or vector container.
推荐答案
正如你所说的,我会告诉你我将如何做这样的事情。否则, stringstream
是真的要走。
听起来你想创建一个streambuf实现,然后写入向量/ deque。这样的东西(复制从我的另一个答案,定向/ dev / null stream ):
Sounds like you want to create a streambuf implementation that then writes to a vector / deque. Something like this (copying from another answer of me that targeted a /dev/null stream):
template<typename Ch, typename Traits = std::char_traits<Ch>,
typename Sequence = std::vector<Ch> >
struct basic_seqbuf : std::basic_streambuf<Ch, Traits> {
typedef std::basic_streambuf<Ch, Traits> base_type;
typedef typename base_type::int_type int_type;
typedef typename base_type::traits_type traits_type;
virtual int_type overflow(int_type ch) {
if(traits_type::eq_int_type(ch, traits_type::eof()))
return traits_type::eof();
c.push_back(traits_type::to_char_type(ch));
return ch;
}
Sequence const& get_sequence() const {
return c;
}
protected:
Sequence c;
};
// convenient typedefs
typedef basic_seqbuf<char> seqbuf;
typedef basic_seqbuf<wchar_t> wseqbuf;
您可以这样使用:
seqbuf s;
std::ostream os(&s);
os << "hello, i'm " << 22 << " years old" << std::endl;
std::vector<char> v = s.get_sequence();
如果你想要一个deque作为序列,你可以这样做:
If you want to have a deque as sequence, you can do so:
typedef basic_seqbuf< char, char_traits<char>, std::deque<char> > dseq_buf;
或类似的东西...我没有测试过。但也许这也是一件好事 - 所以如果它仍然包含错误,你可以尝试修复它们。
Or something similar... Well i haven't tested it. But maybe that's also a good thing - so if it contains still bugs, you can try fixing them.
这篇关于创造一个ostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!