Writing a long series of "static if ... else" statements can be tedious and I'm prone to leaving out the crucial "static" after "else", so I was wondered if it was possible to write a template that would resemble the switch statement, but for types.

Closest I came up to was this:

  void match(T, Fs...)() {
    foreach (F; Fs) {
      static if (isFunctionPointer!F) {
        alias Ps = Parameters!F;
        static if (Ps.length == 1) {
          static if (is(Ps[0] == T)) F(Ps[0].init);
        }
      }
    }
  }

  void test(T)(T t) {
    match!(T,
      (int _) => writeln("Matched int"),
      (string _) => writeln("Matched string")
    );
  }

But that's pretty limited and I'd like to be able to match on whether a type derives from T as well. I just can't figure it out.

Something like this would be ideal...

  match!(T,
    int => writeln("Matched int"),
    is(T : SomeObject) => writeln("Derives from SomeObject")
  );

Anyone able to improve on it?

Reply via email to