Bug 4508 – tuples should be indexable with foreach over range

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
Other
OS
Windows
Creation time
2010-07-26T09:53:12Z
Last change time
2018-05-17T16:32:04Z
Assigned to
No Owner
Creator
David Simcha

Comments

Comment #0 by dsimcha — 2010-07-26T09:53:12Z
The following should really work, as long as the bounds of the foreach loop are known at compile time: import std.typecons; void main() { auto tup = tuple(1, "foo", 3.0).expand; foreach(i; 0..tup.length) { auto val = tup[i]; } }
Comment #1 by bearophile_hugs — 2014-10-11T11:21:01Z
I think this is a bad idea, in this form. So I suggest to close this issue. I prefer this syntax much more: static foreach(i; 0..tup.length) {
Comment #2 by nick — 2017-04-20T12:11:21Z
`foreach (e; seq)` works at compile time for an AliasSeq, so I don't see why `foreach (i; low..high)` can't make `i` known at compile-time if the bounds are known. I think we should rename this bug to apply to any CT-knowable index in a ForeachRangeStatement.
Comment #3 by ag0aep6g — 2017-04-20T16:10:55Z
(In reply to Nick Treleaven from comment #2) > `foreach (e; seq)` works at compile time for an AliasSeq, so I don't see why > `foreach (i; low..high)` can't make `i` known at compile-time if the bounds > are known. Can `i` be made known at compile-time without unrolling the loop (in the binary)? Surely we don't want to unroll every loop that can possibly be unrolled. For example, it would be very surprising if the compiler unrolled a loop like `foreach (i; 0 .. uint.max) writeln(i);`, generating gigabytes of machine code.
Comment #4 by nick — 2017-04-22T07:52:54Z
In that case, perhaps we could use `static foreach` as in comment 1.
Comment #5 by dmitry.olsh — 2018-05-17T16:32:04Z
With static foreach you can do this, and AFAICT is exactly what is required: import std.typecons; void main() { auto tup = tuple(1, "foo", 3.0).expand; static foreach(i; 0..tup.length) {{ auto val = tup[i]; }} }