How to iterate using foreach on a class?

Jonathan M Davis jmdavisProg at gmx.com
Fri Nov 1 13:21:45 PDT 2013


On Friday, November 01, 2013 19:32:35 Dmitry Olshansky wrote:
> 01-Nov-2013 16:43, John Colvin пишет:
> > On Friday, 1 November 2013 at 12:37:20 UTC, simendsjo wrote:
> >> 2) opSlice
> >> 3) alias this
> > 
> > arguably these are the same in the context of the foreach loop. Both
> > just provide direct access to the underlying array.
> 
> No quite. I'd say alias this is frankly a bad idea to provide iteration.
> In any case returning naked underlying array is most surely short-sighted.

Pretty much anytime that you're tempted to use alias this, you should 
reconsider. It _does_ have its uses, but implicit conversions tend to cause a 
lot problems - especially in generic code. And in this case, you can simply 
declare opSlice to return the underlying array, so there isn't really any 
benefit to using alias this other than the fact that it saves you a few 
characters (which isn't even vaguely worth the cost IMHO).

> In short we have 2 ways:
> 1) Ranges
> 2) opApply
> 
> And a couple of extra things on _top_ of that to keep in mind:
> 1) Implicit conversion -> hence alias this to a range/opApply type works
> 2) opSlice is called on foreach aggregate if it's not a range or doesn't
> have opApply by itself.

Yeah. Any user-defined type that's iterable via foreach uses either the range 
API or opApply. And in general, unless the range API isn't going to work for 
you, it's recommended to use the range API rather than opApply. opSlice comes 
into play when you want to iterate over something as a range without consuming 
it. The most common place to see opSlice would likely be on containers.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list