C++ Logo

std-proposals

Advanced search

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

From: Peter C++ <peter.cpp_at_[hidden]>
Date: Mon, 1 Feb 2021 19:10:13 +0100
Stream objects cannot be copied. That would be the safe workaround.

OTOH the following would compile...

template<typename T>
auto print_vector( const vector<T> & v )
{
    return copy( begin(v), end(v), ostream_iterator<int>(
 stringstream{}=stringstream{},// assignment returns lvalue to temp.
 ", " ) );
}

sent from a mobile device so please excuse strange words due to autocorrection.
Peter Sommerlad
peter.cpp_at_[hidden]
+41-79-432 23 32

> On 1 Feb 2021, at 09:11, Marco Fantozzi via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> 
>
> Sorry, but I fail to see why the above is more dangerous than taking a reference to a member of any temporary...
>
> Cheers.
>
>
>> Il giorno dom 31 gen 2021 alle ore 23:00 Dvir Yitzchaki <dvirtz_at_[hidden]> ha scritto:
>> this is dangerous because it’s easy to create a dangling reference if not consumed immediately, e.g.
>>
>> template<typename T>
>> std::string print_vector( const vector<T> & v )
>> {
>> const auto& stream = copy( begin(v), end(v), ostream_iterator<int>( stringstream{}, ", " ) ).stream();
>> return stream.str(); // dangling
>> }
>>
>>> On Sun, 31 Jan 2021 at 18:26, Marco Fantozzi via Std-Proposals <std-proposals_at_[hidden]> wrote:
>>> Hello,
>>>
>>> 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 std::ostream_iterator,
>>> 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
>>>
>>> Thanks
>>>
>>> --
>>> Trinetra
>>> --
>>> Std-Proposals mailing list
>>> Std-Proposals_at_[hidden]
>>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>
>
> --
> Marco Fantozzi
>
>
>
> --
> --
> Marco Fantozzi
> cell +39 320 9322942
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2021-02-01 12:10:21