opApply not called for foeach(container)

monarch_dodra monarch_dodra at gmail.com
Wed Jul 11 07:42:49 PDT 2012


On Wednesday, 11 July 2012 at 14:10:35 UTC, 
travert at phare.normalesup.org (Christophe Travert) wrote:
> I think foreach should never call opSlice. That's not in the 
> online
> documentation 
> (http://dlang.org/statement.html#ForeachStatement), unless
> I missed something. If you want to use foreach on a class with 
> an
> opSlice, then yes, you should define opApply. Otherwise, the 
> user have
> to call opSlice himself, which seems reasonable. That's how I 
> understand
> the doc.

Hum... One thing is for sure, it _does_ call opSlice when it is 
defined.

I just re-read the docs you linked to, and if that was my only 
source, I'd reach the same conclusion as you. 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.


More information about the Digitalmars-d mailing list