foreach with a default range

weaselcat via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 11 05:01:49 PDT 2015


On Thursday, 11 June 2015 at 08:24:25 UTC, Dmitry Olshansky wrote:
> 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[]) {}

I had no idea this worked. Is this documented anywhere?


More information about the Digitalmars-d mailing list