D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 1642 - static foreach support for arrays
Summary: static foreach support for arrays
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86 All
: P3 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2007-11-06 06:53 UTC by Neia Neutuladh
Modified: 2018-01-03 09:27 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Neia Neutuladh 2007-11-06 06:53:18 UTC
The following is required to be executed at compile time, and all data is available at compile time:

int foo () {
    foreach (string letter; ["a", "b", "c"])
        pragma (msg, letter);
    return 0;
}
static const int i = foo();

The expected output when compiling is:
a
b
c

The actual result when compiling is:
foreach_array.d(5): Error: string expected for message, not 'letter'

The issue: static foreach only works for tuples, and I want to use it on an array.

This is inconsistent with __traits: the allMembers trait returns an array. If it returned a more obtuse structure, a tuple, then I wouldn't need to use recursion with it; and if static foreach supported arrays, that would make even more code more readable.
Comment 1 Neia Neutuladh 2007-11-06 21:18:06 UTC
Daniel Keep wrote:
> Currently, there's no such thing as "static foreach".  That the foreach
> is unrolled at compile-time is simply a side-effect of the aggregate
> being a tuple.
> 
> Walter has already indicated that a true static foreach is planned for 2.x.

Now he has a ticket to keep track of it, then :)

Comment 2 Simen Kjaeraas 2010-05-10 01:51:48 UTC
This template lets you iterate through a compile-time array as a tuple. Not as good as the real thing, but might be worth having around.

template ArrayToTuple( alias T ) {
	static if( T.length > 1 ) {
		alias TypeTuple!( T[ 0 ], ArrayToTuple!( T[ 1..$ ] ) ) ArrayToTuple;
	} else {
		alias TypeTuple!( T[ 0 ] ) ArrayToTuple;
	}
}
Comment 3 bearophile_hugs 2010-05-10 03:55:47 UTC
See also bug 4085
Comment 4 Simen Kjaeraas 2018-01-03 09:27:01 UTC
Fixed in 2.076 with static foreach.