http://d.puremagic.com/issues/show_bug.cgi?id=10712
[email protected] changed: What |Removed |Added ---------------------------------------------------------------------------- CC| |[email protected] --- Comment #1 from [email protected] 2013-07-25 03:12:47 PDT --- (In reply to comment #0) > Sometimes it's neccessary to organize compiletime loop/unroll another loop for > better perfomance. > > I'd make that simple template: > > template IndexTuple(int e, int s = 0, T...) { > static if(s == e) > alias IndexTuple = T; > else > static if(s > e) > alias IndexTuple = IndexTuple!(e, s - 1, T, s); > else > alias IndexTuple = IndexTuple!(e, s + 1, T, s); > } > > Use: > foreach(idx; IndexTuple!10) > writeln(idx); // prints 0, 1, ..., 9 > > foreach(idx; IndexTuple!(10, 2)) > writeln(idx); // prints 2, 3, ..., 9 > > foreach(idx; IndexTuple!-10) > writeln(idx); // prints 0, -1, ..., -9 It think this already exists in phobos somewhere, though I don't remember where though, and it probably wasn't good for public use. In any case, I think the useage should more closely resemble what iota does. For example: IndexTuple!(2, 10)) vs IndexTuple!(10, 2)) or IndexTuple!(0, -10, -1)) vs IndexTuple!(0, -10)) Arguably, iota accepts "iota(10)", but I (and others) think that is a retarded idea, when typing "iota(0, 10)", is just and easy. I think we should avoid making the same mistakes. Also, it should be parameterizable on iteration type. Here is a rough sketch of an implementation that does this. import std.stdio, std.traits; template IndexTuple(alias l, alias h) { alias IndexTuple = IndexTupleImpl!(l, h, 1); } template IndexTuple(alias l, alias h, alias inc) { alias IndexTuple = IndexTupleImpl!(l, h, inc); } template IndexTupleImpl(alias l, alias h, alias inc, T...) { alias E = CommonType!(l, h, inc); static if (inc == 0) static assert(0, "increment must be non-0"); else static if (inc > 0 && l >= h) alias IndexTupleImpl = T; else static if(inc < 0 && l <= h) alias IndexTupleImpl = T; else alias IndexTupleImpl = IndexTupleImpl!(cast(E)(l + inc), h, inc, T, l); } void main() { foreach(idx; IndexTuple!(0, 0)) write(idx, ' '); // prints writeln(); foreach(idx; IndexTuple!(0, 10)) write(idx, ' '); // prints 0, 1, ..., 9 writeln(); foreach(idx; IndexTuple!(2, 10)) write(idx, ' '); // prints 2, 3, ..., 9 writeln(); foreach(idx; IndexTuple!(0, -10, -1)) write(idx, ' '); // prints 0, -1, ..., -9 writeln(); foreach_reverse(idx; IndexTuple!(-9, 1)) write(idx, ' '); // prints 0, -1, ..., -9 writeln(); foreach(idx; IndexTuple!(0.5, 10)) write(idx, ' '); // prints 0.5, 1.5, ..., 9.5 writeln(); foreach(idx; IndexTuple!(0, 1, 0.1)) write(idx, ' '); // prints 0 0.1 ... 0.9 writeln(); foreach(idx; IndexTuple!('a', cast(char)('z' + 1), cast(char)1)) write(idx, ' '); // prints a b ... z writeln(); } -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: -------
