C++ Logo

std-proposals

Advanced search

Re: [std-proposals] contiguous_iterator is too restrictive in C++26 std::optional<T&>

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Fri, 16 Aug 2024 10:04:14 -0400
On Fri, Aug 16, 2024 at 8:00 AM Piotr Nycz via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hi,
>
> I have a small request(bug fix? improvement) to existing (probably accepted already) proposals to C++26 about std::optional class.
>
> I am pretty sure (I tested it) that contiguous_iterator as specified in this paper Give std::optional Range Support is too restrictive as for next proposal - std::optional<T&>
> In my opinion it should be just input_iterator.
>
> The main reason is that for input_iterator I wouldn't need to have T defined - it can still be forward declared - thus compilation time will not have to increase - nor I have to add any extra includes when changing from:
>
> struct Some;
> void func(Some&);
> std::optional<Some&> a = get();
>
> if (a) func(*a);
>
> to:
>
> ...
> for (auto& v: a) func(v);

I would argue that you shouldn't do that at all; that's not really the
point of allowing an `optional` to be a range. It obfuscates the clear
meaning of the original code.

> The other reasons - who would care if the iterator type to 0-or-1 range is contiguous or not, then no need to complicate...

A contiguous range is convertible to a pointer range or a span. Input
ranges are not. There are many interfaces which require contiguous
ranges. From a user-perspective, there is no reason why a rangified
optional<T> should not be contiguous (and thus usable with code that
requires contiguous ranges).

Received on 2024-08-16 14:04:28