User defined forward range - foreach initializes f.r.

Andre via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 13 11:29:51 PDT 2014


Am 13.06.2014 20:22, schrieb H. S. Teoh via Digitalmars-d-learn:
> [...]
>
> Generally, it's a bad idea to conflate a container with a range over its
> contents. In this sense, built-in arrays are a very bad example, because
> they show precisely this sort of conflation. But they get away with it
> because of their hybrid value/reference semantics. Most containers,
> however, don't have this sort of complex semantics, so they don't mix
> very well with ranges directly.
>
> It's much better to separate the container from a range over its
> contents. So I wouldn't put the range API methods in the List class, but
> implement an opSlice method that returns a struct that performs the list
> iteration, that implements the range API. This allows you to write:
>
> 	auto myList = new List(...);
> 	foreach (item; myList[]) { // N.B., myList[] calls myList.opSlice()
> 		...
> 	}
>
> Since the range struct returned by opSlice is separate from the
> container itself, you don't have any risk of iteration also consuming
> the container.
>
>
> T
>

Thank you, this information is really helpful.

Kind regards
André



More information about the Digitalmars-d-learn mailing list