opNext: Simplified ranges

Steven Schveighoffer schveiguy at gmail.com
Sat Nov 5 15:17:42 UTC 2022


On 11/5/22 2:01 AM, Tomer at Weka wrote:
> Today I even ran into a problem that cannot be solved using the existing 
> protocol: a consuming range (think a file stream) that should not 
> consume the element if the foreach has been broken.

Not sure what this means. breaking a foreach does not consume the next 
element.

Now, foreach *does* make a copy of the range. Which means that the copy 
is going to consume the current, while the original will not get it (and 
the copy is gone once the loop is over).

This can be solved by a wrapper:

```d
struct RefOf(T)
{
   private T *_val;
   ref T _get() { return *_val; }
   alias _get this;
}

auto refOf(T)(return ref T val) { return RefOf!T(&val); }

foreach(elem; range.refOf) // now doesn't make a copy.
```

Could also be solved with syntax changes to foreach. Maybe 
`foreach(elem; ref range)`?

-Steve


More information about the Digitalmars-d mailing list