C++ Logo


Advanced search

A 'stream()' member for std::ostream_iterator and cousins

From: Marco Fantozzi <marco.fantozzi_at_[hidden]>
Date: Sun, 31 Jan 2021 17:25:19 +0100

I'm new to the newsletter, so I might not be in line with standard
netiquette here... In case please make me aware of my shortcomings, thanks

I noticed that it is not possible to retrieve the output stream used by a
even if it would be useful in a few contexts like the following example:

std::string print_vector( const std::vector<int> & v )
    std::stringstream s;
    copy( begin(v), end(v), std::ostream_iterator<int>( s, ", " ) );
    return s.str();

If there was a method ostream_iterator<...>::stream() that returns the
reference to the stream captured by the iterator,
it would be possible to make the above code more concise:

template<typename T>
std::string print_vector( const vector<T> & v )
    return copy( begin(v), end(v), ostream_iterator<int>( stringstream{},
", " ) ).stream().str();

Naturally the extension should apply to all input/output iterator facades
in the STL



Received on 2021-01-31 10:25:34