static switch/pattern matching

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 25 05:35:39 PDT 2016


On Saturday, 25 June 2016 at 12:30:22 UTC, Lodovico Giaretta 
wrote:
> If you want this to work, you need your lambdas to take the 
> casted value as a parameter:
>
>    void test(T)(T value) {
>      int i;
>      string s;
>      match!(value,
>        int, (val) => i = val,
>        string, (val) => s = val
>      );
>    }
>
> And of course you need to modify match! for this to work.

Something like this:

    void match(alias t, cases...)() {
      static if (cases.length == 1) cases[0]();
      else static if (cases.length > 2) {
        static if (is(typeof(cases[0]) == bool)) {
          static if (cases[0]) cases[1](t);
          else match!(t, cases[2 .. $]);
        }
        else static if (is(typeof(t) == cases[0])) cases[1](t);
        else match!(t, cases[2 .. $]);
      }
    }

    void test(T)(T value) {
      int i;
      string s;
      match!(value,
        int, (val) => i = val,
        string, (val) => s = val
      );
    }

    void main()
    {
      test(1);
      test("A string");
    }


More information about the Digitalmars-d-learn mailing list