opApply not called for foeach(container)

Christophe Travert travert at phare.normalesup.org
Wed Jul 11 07:10:35 PDT 2012


"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.

-- 
Christophe


More information about the Digitalmars-d mailing list