opApply not called for foeach(container)

Christophe Travert travert at phare.normalesup.org
Wed Jul 11 08:43:13 PDT 2012


"monarch_dodra" , dans le message (digitalmars.D:171902), a écrit :
> I just re-read the docs you linked to, and if that was my only 
> source, I'd reach the same conclusion as you.

I think the reference spec for D should be the community driven and 
widely available website, not a commercial book. But that's not the 
issue here.

> however, my "The D 
> Programming Language", states:
> *12: Operator Overloading
> **9: Overloading foreach
> ***1: foreach with Iteration Primitives
> "Last but not least, if the iterated object offers the slice 
> operator with no arguments lst[], __c is initialized with lst[] 
> instead of lst. This is in order to allow ?extracting? the 
> iteration means out of a container without requiring the 
> container to define the three iteration primitives."
> 
> Another thing I find strange about the doc is: "If the foreach 
> range properties do not exist, the opApply method will be used 
> instead." This sounds backwards to me.

Skipping the last paragraph, a reasonable interpretation would be that 
foreach try to use, in order of preference:
 - for each over array
 - opApply
 - the three range primitives (preferably four if we include save)
 - opSlice (iteration on the result of opSlice is determined by the same 
system).

 opApply should come first, since if someone defines opApply, he or she 
obviously wants to override the range primitive iteration.
 opApply and range primitives may be reached via an alias this.
 opSlice is called only if no way to iterate the struct/class is found. 
 I would not complain if the fourth rule didn't exist, because it's not 
described in dlang.org, but it is a reasonable feature that have be 
taken from TDPL (but then it should be added in dlang.org).


This way, if arr is a container that defines an opSlice, and that does 
not define an opApply, and does not define range primitives:

foreach (a, arr) ...
and
foreach (a, arr[]) ...
should be stricly equivalent. Since the first is translated into the 
second. Both work only if arr[] is iterable.

I think you hit a bug.

-- 
Christophe


More information about the Digitalmars-d mailing list