static foreach
bearophile
bearophileHUGS at lycos.com
Sun Mar 28 14:17:38 PDT 2010
Navin Kumar:
> I was going over the D tutorials on tuples and noticed that it's possible to do a "foreach" across the tuple items. I'm assuming this is a compile-time foreach, is that correct?
Correct.
> I would like to solve this problem with a compile-time foreach; how do I do so? "static foreach" is not valid syntax in D.
In my dlibs1 I have:
template Range(int stop) {
static if (stop <= 0)
alias Tuple!() Range;
else
alias Tuple!(Range!(stop-1), stop-1) Range;
}
/// ditto
template Range(int start, int stop) {
static if (stop <= start)
alias Tuple!() Range;
else
alias Tuple!(Range!(start, stop-1), stop-1) Range;
}
/// ditto
template Range(int start, int stop, int step) {
static assert(step != 0, "Range: step must be != 0");
static if (step > 0) {
static if (stop <= start)
alias Tuple!() Range;
else
alias Tuple!(Range!(start, stop-step, step), stop-step) Range;
} else {
static if (stop >= start)
alias Tuple!() Range;
else
alias Tuple!(Range!(start, stop-step, step), stop-step) Range;
}
} // End Range!(a,b,c)
With that you can unroll loops and push multiple cases inside a switch statement.
With a little more work you can unroll in cases where you don't know the number of loops, using a modulus and vision approach.
The main problem, baside a bit of bloat at compile time, is that such forach(i; Range!(...)) doesn't work outside functions, as a good static foreach has to.
Bye,
bearophile
More information about the Digitalmars-d
mailing list