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 by dhasenan — 2007-11-06T21:18:06Z
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 by simen.kjaras — 2010-05-10T01:51:48Z
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 by bearophile_hugs — 2010-05-10T03:55:47Z