creating an ostream

前端 未结 4 590
走了就别回头了
走了就别回头了 2021-01-05 08:09

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 08:44

    As it is for education, as you say, i will show you how i would do such a thingy. Otherwise, stringstream is really the way to go.

    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 Sequence = std::vector >
    struct basic_seqbuf : std::basic_streambuf {
         typedef std::basic_streambuf 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 seqbuf;
    typedef basic_seqbuf wseqbuf;
    

    You can use it like this:

    seqbuf s;
    std::ostream os(&s);
    os << "hello, i'm " << 22 << " years old" << std::endl;
    std::vector v = s.get_sequence();
    

    If you want to have a deque as sequence, you can do so:

    typedef basic_seqbuf< char, char_traits, std::deque > 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.

提交回复
热议问题