static switch/pattern matching

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 25 02:07:19 PDT 2016


On Saturday, 25 June 2016 at 08:46:05 UTC, John wrote:
> 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?

Instead of passing functions to match!, pass pairs of arguments, 
like this:

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

Now, in the implementation, foreach pair of arguments, if the 
first member is a type that matches your target, perform that 
branch; otherwise, if the first member is a boolean value, and it 
is true, perform the branch.


More information about the Digitalmars-d-learn mailing list