C++ Logo

std-proposals

Advanced search

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

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Fri, 16 Aug 2024 11:25:02 -0400
On Fri, Aug 16, 2024 at 10:04 AM Jason McKesson via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On Fri, Aug 16, 2024 at 8:00 AM Piotr Nycz via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
> >
> > 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.
>

Right. Now, I do think a lot of people *are* going to do exactly that — I
think a lot of WG21 members voted for the paper because they *want* to do
exactly that — but that still doesn't make it something that you *should*
want to do. (Similarly, CTAD: people voted for it because they wanted to do
it, but you *should* not do it.)

> > In practice it is also easier to implement input iterator, not to
mention less code to write

Well, that's not true. In practice, the contiguous iterators returned from
`optional::begin` and `optional::end` can be plain old `T*`:
  T *begin() { return &payload_; }
  T *end() { return &payload_ + 1; }
Strangely Beman.Optional26
<https://github.com/beman-project/Optional26/blob/main/include/Beman/Optional26/optional.hpp>
fails to do this; they *do* pay all the extra LoC for a custom iterator
class type.
But, on the third hand, every library vendor implementing this paper will
already have a custom contiguous iterator type, which they use for e.g.
vector::iterator — libc++ calls it `__wrap_iter<T*>`. So in practice,
library vendors will just do
  using iterator = __wrap_iter<T*>;
  iterator begin() { return iterator(&payload_); }
  iterator end() { return iterator(&payload_ + 1); }
which is still no additional LoC. In fact it's *fewer* LoC than your idea
of writing a custom input-iterator class type just for this purpose.

–Arthur

Received on 2024-08-16 15:25:16