Range Redesign: Copy Semantics

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jan 23 05:57:25 UTC 2024


On Sunday, January 21, 2024 7:51:33 AM MST Paul Backus via Digitalmars-d 
wrote:
> On Sunday, 21 January 2024 at 05:00:31 UTC, Jonathan M Davis
>
> wrote:
> > From what I can see, the main negative is simply that you can't
> > then write code that works on both a basic input range and a
> > forward range (though you can obviously still create function
> > overloads so that the caller can use either)
>
> With the proposed design, it would be possible to implement
> next() for forward ranges as a UFCS function:
>
>      auto next(FR)(FR fr)
>          if (std.v2.range.isForwardRange!FR)
>      {
>          if (fr.empty)
>          {
>              return Nullable!(ElementType!FR).init;
>          }
>          else
>          {
>              scope(success) fr.popFront;
>              return nullable(fr.front);
>          }
>      }
>
> So, a function written to operate on basic input ranges would be
> able to accept any kind of range, same as today.

Actually. What occurs to me is that if we made this function take the range
by pointer, then it would be possible to give a forward range the correct
copy semantics. You'd then have to take its address (or put it on the heap)
to make it work, but then you'd get reference semantics even though it's a
forward range.

Obviously, that's less than ideal if you want a function to accept both
basic input ranges and forward ranges, but if it's a function that really
only needs basic input ranges and doesn't benefit from operating on a
forward range, then it would be simple enough to create an overload which
takes the address - and if you really want to be returning the range from
the function, then you wouldn't want it to be operating on both basic input
ranges and forward ranges anyway, since you'd usually be looking to wrap the
result, in which case, you'd need to do all of the annoying static ifs to
determine which functions from the range API you could slap on the wrapper
range based on the capabilities of the one being passed in.

- Jonathan M Davis





More information about the Digitalmars-d mailing list