Unexpected foreach lowering

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 10 11:12:42 PDT 2016


On Wednesday, 10 August 2016 at 18:08:02 UTC, Lodovico Giaretta 
wrote:
> I'm probably missing something stupid but...
> Why on earth do the two loops in main print a different result?
> It looks like the foreach lowering is ignoring my definition of 
> front...
>
> =====================================================
> import std.stdio, std.container.array;
>
> struct RangeWrapper(Range)
> {
> 	Range range;
> 	alias range this;
> 	
> 	auto front()
> 	{
> 		return range.front + 1;
> 	}
> }
> auto rangeWrapper(Range)(auto ref Range range)
> {
> 	return RangeWrapper!Range(range);
> }
>
> void main()
> {
> 	Array!int array;
> 	array.insertBack(3);
> 	
> 	foreach (i; rangeWrapper(array[]))
> 		writeln(i);           // prints 3, which is wrong
> 	
>         // isn't the above foreach equivalent to the following 
> loop ?
>
> 	for (auto r = rangeWrapper(array[]); !r.empty; r.popFront())
> 		writeln(r.front);     // correctly prints 4
> }
> =====================================================
>
> Thank you for your help.

This actually only happens with std.container.Array. Other ranges 
are ok. Even stranger...


More information about the Digitalmars-d-learn mailing list