创造一个ostream

5 c++ std ostream

我出于教育原因试图创建一个c ++ ostream.我的测试将创建一个像流一样的ostream,除了写入一个文件,它将写入双端队列或向量容器.

Joh*_*itb 11

就像你说的那样,我会告诉你我将如何做这样的事情.否则,stringstream真的是要走的路.

听起来你想要创建一个streambuf实现,然后写入vector/deque.像这样的东西(从我的另一个回答中复制,目标是/ dev/null流):

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;
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

seqbuf s;
std::ostream os(&s);
os << "hello, i'm " << 22 << " years old" << std::endl;
std::vector<char> v = s.get_sequence();
Run Code Online (Sandbox Code Playgroud)

如果你想要一个deque作为序列,你可以这样做:

typedef basic_seqbuf< char, char_traits<char>, std::deque<char> > dseq_buf;
Run Code Online (Sandbox Code Playgroud)

或类似的东西......好吧,我没有测试过它.但也许这也是一件好事 - 所以如果它仍然包含bug,你可以尝试修复它们.