static switch/pattern matching

John via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 25 01:46:05 PDT 2016


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?


More information about the Digitalmars-d-learn mailing list