opApply not called for foeach(container)

monarch_dodra monarch_dodra at gmail.com
Wed Jul 11 03:20:26 PDT 2012


If you create a class/struct that can give you a (forward) range 
via "opSlice()", and that range gives you access to "opApply", 
then you get two different behaviors:

----
MyClass arr = ...;

foreach(a; arr)
    ...

foreach(a; arr[])
    ...

----
In the first case, foreach will call opSlice(), and then walk 
through the resulting arr[] range with the front/popFront/empty 
troika.

In the second case, foreach will call opApply on the range 
"arr[]".

----
I'm wondering if this is the correct behavior? In particular, 
since foreach guarantees a call to opSlice(), so writing "arr[]" 
*should* be redundant, yet the final behavior is different.

That said, the "issue" *could* be fixed if the base class defines 
opApply as: "return opSlice().opApply(dg)" (or more complex). 
However:
a) The implementer of class has no obligation to do this, since 
he has provided a perfectly valid range.
b) This would force implementers into more generic useless 
boilerplate code.

What are your thoughts? Which is the "correct" solution? Is it a 
bug with foreach, or should the base struct/class provide an 
opApply?

PS: Related: "foreach over range (with opApply) should save 
range."
http://d.puremagic.com/issues/show_bug.cgi?id=4347
On this assigned issue, is the conclusion that foreach will 
eventually save the range?


More information about the Digitalmars-d mailing list