User defined forward range - foreach initializes f.r.

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


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.

unittest
{
	auto intList = new List!int(1,2,3);
	assert(intList.length == 3);
	foreach(item; intList) {}
	assert(intList.length == 3);
}


class List(T)
{
	private T[] items;
	
	this(T[] items...)
	{
		this.items = items;
	}

	bool empty() const
     {
         return items.length == 0;
     }
	
	@property int length() const
	{
		return items.length;
	}

     void popFront()
     {
         items = items[1..$];
     }
	
	@property List!T save() const
	{
		return new List!T( cast(T[]) items);
	}

	T front() const
     {
         return opIndex(0);
     }
	
	T opIndex(size_t index) const
     {
         return cast(T) items[index];
     }
}

I already tried different thinks, like using dup or importing std.array.
But nothing helps, the unittest fails.
Why it fails?

Kind regards
André


More information about the Digitalmars-d-learn mailing list