range algorithms on container class
Alex Burton
ab at bab.com
Wed Jan 15 04:15:13 UTC 2020
On Thursday, 9 January 2020 at 10:26:07 UTC, Jonathan M Davis
wrote:
> On Wednesday, January 8, 2020 10:56:20 PM MST rikki cattermole
> via Digitalmars-d-learn wrote:
>> Slicing via the opSlice operator overload is a convention, not
>> a requirement.
>
> It's not a requirement, but it's more than a convention. If you
> use the container with foreach, the compiler will call opSlice
> on the container to get a range. So, there's no need to
> implement opApply to iterate over a container with foreach. You
> could choose to implement a container with opApply and use a
> function other than opSlice for getting a range, but the
> compiler understands enough to try to slice the container for
> you automatically when using it with foreach.
>
> - Jonathan M Davis
Implementing opApply allowed me to use foreach on the container.
I would expect that returning a slice would not be logically
possible for many container types. A slice cannot be a range
either, otherwise you would need to call the array algorithm to
assign a slice of an array to another array.
So the compiler must be creating a forward iterating range to
pass into the range algorithms in these cases.
That foreach, and range algorithms can work on a native array but
only foreach can work on custom container type looks like a gap
in the language.
More information about the Digitalmars-d-learn
mailing list