How to iterate using foreach on a class?

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 5 20:54:39 PST 2013


On Sunday, November 03, 2013 14:28:13 Nicolas Sicard wrote:
> > So we basically have 4 ways..?
> > 1) popFront + front
> > 2) opSlice
> > 3) alias this
> > 4) opApply
> 
> How about having a nested struct implementing a range interface +
> a method (@property) returning it + alias this on the property?
> 
> http://dpaste.dzfl.pl/230061d2

alias this should be avoided as much as possible. It's a bug magnet - 
especilaly when generic code is involved. And there's no reason to create a 
new range type in this case, because all that needs to be iterated over is the 
array. It makes by far the most sense to simply treat the class as a 
container, and overload opSlice so that it returns the array to be iterated 
over. If there was ever a need to do something more complicated than just 
iterate over the array, then a new range type could be returned from opSlice 
instead, but as it stands simply returning the array would be just fine.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list