Bug 2411 – Reference Tuple Foreach

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2008-10-09T15:06:00Z
Last change time
2015-06-09T01:20:17Z
Keywords
patch
Assigned to
nobody
Creator
dsimcha

Comments

Comment #0 by dsimcha — 2008-10-09T15:06:44Z
Sometimes, when iterating over a tuple representation of a class or struct, I want to modify the class/struct contents. Ex: struct S { uint foo = 1; } void main() { S s; foreach(element; s.tupleof) element = 2; writeln(s.foo); //Still prints 1 } It would be nice if I could do something like: foreach(ref element; s.tupleof) and this would modify s.foo.
Comment #1 by dsimcha — 2009-06-02T05:51:21Z
*** Issue 3045 has been marked as a duplicate of this issue. ***
Comment #2 by bearophile_hugs — 2010-03-07T10:28:09Z
Bug 3835 is a partial duplicate of this (one case seems different).
Comment #3 by hoganmeier — 2010-05-20T15:12:01Z
This is a workaround: foreach (i, dummy ; s.tupleof) s.tupleof[i] = 2;
Comment #4 by k.hara.pg — 2012-01-01T08:28:16Z
Comment #5 by k.hara.pg — 2012-01-01T08:31:04Z
My patch requires explicit 'ref'. void main() { S s; // foreach( element; s.tupleof) // doesn't work foreach(ref element; s.tupleof) // OK element = 2; assert(s.foo == 2); }
Comment #6 by dsimcha — 2012-01-01T13:44:46Z
(In reply to comment #5) > My patch requires explicit 'ref'. > > void main() { > S s; > // foreach( element; s.tupleof) // doesn't work > foreach(ref element; s.tupleof) // OK > element = 2; > assert(s.foo == 2); > (In reply to comment #5) > My patch requires explicit 'ref'. > > void main() { > S s; > // foreach( element; s.tupleof) // doesn't work > foreach(ref element; s.tupleof) // OK > element = 2; > assert(s.foo == 2); > } It seems to me like the only logical way to do this is to require explicit ref. The semantics should be the same as foreach over ranges. Nice work.
Comment #7 by bugzilla — 2012-01-10T12:25:30Z