User defined forward range - foreach initializes f.r.

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 13 11:22:10 PDT 2014


On Fri, Jun 13, 2014 at 08:14:11PM +0200, Andre via Digitalmars-d-learn wrote:
> Hi,
> 
> I have a template class "List" which should provide generic list
> functionality. In my use case, using a class instead a struct
> is more comfortable.
> 
> Following unittest fails, although the forward range
> implements the save method.
[...]

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

-- 
Let X be the set not defined by this sentence...


More information about the Digitalmars-d-learn mailing list