foreach() behavior on ranges

frame frame86 at live.com
Tue Aug 24 08:36:18 UTC 2021


Consider a simple input range that can be iterated with empty(), 
front() and popFront(). That is comfortable to use with foreach() 
but what if the foreach loop will be cancelled? If a range isn't 
depleted yet and continued it will supply the same data twice on 
front() in the next use of foreach().

For some reason, foreach() does not call popFront() on a break or 
continue statement. There is no way to detect it except the range 
itself tracks its status and does an implicit popFront() if 
needed - but then this whole interface is some kind of useless.

There is opApply() on the other hand that is designed for 
foreach() and informs via non-0-result if the loop is cancelled - 
but this means that every range must implement it if the range 
should work in foreach() correctly?

This is very inconsistent. Either foreach() should deny usage of 
ranges that have no opApply() method or there should be a reset() 
or cancel() method in the interfaces that may be called by 
foreach() if they are implemented.

How do you handle that issue? Are your ranges designed to have 
this bug or do you implement opApply() always?


More information about the Digitalmars-d-learn mailing list