foreach with a default range

Dmitry Olshansky via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 11 01:24:11 PDT 2015


On 11-Jun-2015 11:18, w0rp wrote:
> A thought just came to me. When I'm implementing foreach for a
> container, I'm left with the choice of using a range for a container or
> opApply. I've found often that I prefer the ranges, as it's easy for me
> to write a range that satisfies @nogc @safe pure nothrow, etc. This is
> because the ranges don't call delegates which are less restrictive,
> which opApply does.
>
> I've been thinking about how you would implement opApply so that it
> could allow you to run @system code while the iteration itself is @safe,
> but then I had another idea. Could we allow foreach to look for a method
> (UFCS include) for producing a default range for an object, from a
> function named 'range'?
>
> In short this...
>
> foreach(elem; container) {}
>
> Could be transformed into this.
>
> foreach(elem; container.range()) {}

Already works. Just define opSlice for container that returns a range 
and then:

foreach(elem; container) {}

is lowered to:

foreach(elem; container[]) {}

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list