opApply not called for foeach(container)

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 11 08:11:31 PDT 2012


On Wednesday, July 11, 2012 14:10:35 Christophe Travert wrote:
> "monarch_dodra" , dans le message (digitalmars.D:171868), a écrit :
> > 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?
> 
> 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.

TDPL says that opSplice is called on a type passed to foreach if it defines it. 
Look at pages 380 - 381. The last paragraph of section 12.9.1 explicitly 
mentions it.

- Jonathna M Davis


More information about the Digitalmars-d mailing list