The following should be possible, with x being ref if possible and non-ref otherwise. I've toyed with the possibility of adding opApply support to some stuff in std.range and std.algorithm and this is a blocker for doing it at all properly.
void main() {
foreach(auto ref x; [1, 2]) {}
}
test9.d(2): basic type expected, not auto
test9.d(2): no identifier for declarator int
test9.d(2): found 'auto' when expecting ';'
test9.d(2): found ';' when expecting ')'
test9.d(2): found ')' when expecting ';' following statement
Comment #1 by nfxjfg — 2010-08-21T20:33:05Z
How would this be different from the following (which works)?
void main() {
foreach(ref x; [1, 2]) {}
}
Comment #2 by dsimcha — 2010-08-21T20:49:02Z
Because if the range didn't support ref iteration, the foreach loop would work with non-ref iteration rather than producing a compile time error.(In reply to comment #1)
> How would this be different from the following (which works)?
>
> void main() {
> foreach(ref x; [1, 2]) {}
> }
If the range didn't support ref iteration, the foreach loop would work with non-ref iteration rather than producing a compile time error.
Comment #3 by dsimcha — 2010-08-29T21:33:04Z
Another use case for this is if you are iterating over something that may be expensive to copy. In these cases, doing foreach(elem; stuff) is inefficient because it produces an unnecessary copy, but foreach(ref elem; stuff) isn't generic enough because it won't work on ranges w/o lvalue elements.
Comment #4 by code — 2013-11-01T12:17:39Z
This is still an interesting proposal.
Comment #5 by monarchdodra — 2013-11-02T03:10:11Z
(In reply to comment #4)
> This is still an interesting proposal.
Seconded. Thoguh I do seem to remember that another Bug Report about this was open... I did find this interesting thread about it though: http://forum.dlang.org/thread/[email protected]
This proposal has 2 very important (IMO) ramifications:
First, it would allow making "foreach(ref; range)" illegal, if said range doesn't give ref access. This is a *big* source of bugs.
Second, once we have this, we would be able to write *correct* generic code. Read this extract from "reduce":
// For now, just iterate using ref to avoid unnecessary copying.
// When Bug 2443 is fixed, this may need to change.
foreach (ref elem; r)
{
Or "I'm doing wrong, but it seems to work".
So long story short, if we ever hope to have "ref-correct" foreach, we *must* have "auto ref" to make foreach useable in generic code.
This gets a vote from me
Comment #6 by nick — 2024-08-19T16:00:34Z
`ref` currently works like `auto ref` - see issue 11934. But `auto ref` could be supported now, and the next edition could fix that issue.
Comment #7 by robert.schadek — 2024-12-13T17:53:01Z