range algorithms on container class

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Jan 18 23:17:37 UTC 2020


On Wednesday, January 15, 2020 9:13:05 AM MST Paul Backus via Digitalmars-d-
learn wrote:
> 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
>
> Is this documented in the language spec anywhere? I don't see
> anything about it in the section on foreach [1] or the section on
> slice operator overloading [2].
>
> [1] https://dlang.org/spec/statement.html#foreach-statement
> [2] https://dlang.org/spec/operatoroverloading.html#slice

I don't know if it's in the spec or not, but IIRC, it was in TDPL. Either
way, I'm sure that it's been implemented. IIRC, there was even a bug related
to filter, because it had opSlice implemented on it for some reason when it
really shouldn't have, resulting in unexpected behavior when using the range
with foreach.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list