The future of foreach| arbitrary number of arrays version

downs default_357-line at yahoo.de
Sun Dec 23 06:21:00 PST 2007


Finally. This took entirely too long.
I'll save myself the hassle of indenting it. Have fun! :)
 --downs

module lockstep;
import std.stdio;

template Tuple(T...) { alias T Tuple; }

template ElemType(T) { static assert(false); }
template ElemType(T: T[]) { alias T ElemType; }
template Unstatic(T...) {
  static if (T.length) {
    alias Tuple!(ElemType!(T[0])[], Unstatic!(T[1..$])) Unstatic;
  } else alias Tuple!() Unstatic;
}

template RefParams(int LEN) {
  static if (LEN>1) {
    const int minus1=LEN-1;
    const string def=RefParams!(LEN-1).def~
      ", ref ElemType!(T["~minus1.stringof~"])";
    const string call=RefParams!(LEN-1).call~
      ", a["~minus1.stringof~"][id]";
  } else {
    static assert(LEN);
    const string def="ref ElemType!(T[0])";
    const string call="a[0][id]";
  }
}

struct _lockstep(T...) {
  T a;
  mixin("
    int opApply(int delegate(ref size_t id, "~RefParams!(T.length).def~") dg) {
      foreach (id, bogus; a[0])
        if (auto res=dg(id, "~RefParams!(T.length).call~")) return res;
      return 0;
    }
    int opApply(int delegate("~RefParams!(T.length).def~") dg) {
      foreach (id, ref entry; a[0])
        if (auto res=dg("~RefParams!(T.length).call~")) return res;
      return 0;
    }
  ");
}

_lockstep!(Unstatic!(T)) lockstep(T...)(T p) {
  _lockstep!(Unstatic!(T)) res;
  foreach (id, entry; p) res.a[id]=p[id];
  return res;
}

void main() {
  foreach (entry1, entry2, entry3; lockstep([1, 2, 3], [4, 5, 6], [7, 8, 9]))
    writefln(entry1, " - ", entry2, " - ", entry3);
}



More information about the Digitalmars-d mailing list