On Tue, Aug 31, 2010 at 22:41, Lutger <lutger.blijdest...@gmail.com> wrote:
> > Wait what, we have static foreach? I thought that didn't work out. > > foreach is automatically done at compile-time if you iterate in typetuples string toStrings(Args...)(Args args) //btw, I regularly need this { string result; foreach(i,Type; Args) { result ~= args[i] ~ " "; } return result; } In the above example, I iterate in Args, getting all types and their respective indicex in turn, and use the *compile-time* index i to address the i-th value in the expression tuple args. > I want this to work or something like it, is it possible? > > enum test = [1,2, 3]; > > foreach(i; 0..test.length) { > pragma(msg, to!string(test[i]) ); > } > Well, 0..someEnum is not recognized by the compiler. The workaround is to create a typetuple of the correct length and use it as a support for iteration: template ZeroTo(int to) if (to >= 0) { static if (to == 0) alias TypeTuple!() ZeroTo; else static if (to == 1) alias TypeTuple!(0) ZeroTo; else alias TypeTuple!(ZeroTo!(to-1), to-1) ZeroTo; // here I use the fact that integers are accepted directly as template parameters and that TypeTuple auto-flatten } so ZeroTo!3 is (0,1,2), since I made it a range open on the right. ZeroTo!0 is empty... enum test = [1,2, 3]; foreach(i; ZeroTo!(test.length)) { pragma(msg, to!string(test[i]) ); } The from -> to version is easy, along with a step parameter. Philippe