C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Return type of string_view::remove_suffix

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 6 Jan 2023 11:28:31 -0500
On Fri, Jan 6, 2023 at 10:17 AM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> I had a function like this:
>
> extern void Func(string_view);
>
> And I wanted to call it as follows:
>
> string str("monkey5");
> Func( string_view(str).remove_suffix(1u) ); // remove the '5'
>
> but this didn't compiler because 'remove_suffix' returns void.
>
> Would it not have made sense for 'remove_suffix' to be defined as:
>
> class std::string_view {
> string_view &remove_suffix(size_t) &;
> string_view &&remove_suffix(size_t) &&;
> string_view &remove_prefix(size_t) &;
> string_view &&remove_prefix(size_t) &&;
> };
>
> so that we can do stuff like:
>
> string str("monkey5");
> Func( string_view(str).remove_suffix(1u).remove_prefix(2u) );

You could just do this:

Func(string_view(str.begin()+1, str.end() - 2));

This requires C++20 for the contiguous iterator support, but it does
work. Note that the remove_* functions exhibit UB if you try to remove
more characters than exist. So the fact that this too will exhibit UB
in those situations is fine.

Received on 2023-01-06 16:28:38