static switch/pattern matching
Lodovico Giaretta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jun 25 05:30:22 PDT 2016
On Saturday, 25 June 2016 at 10:39:09 UTC, John wrote:
> Thanks for the help, both. This appeared to work, until I
> realised the lambda isn't static:
>
> void match(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]();
> else match!(T, cases[2 .. $]);
> }
> else static if (is(T == cases[0])) cases[1]();
> else match!(T, cases[2 .. $]);
> }
> }
>
> void test(T)(T value) {
> int i;
> string s;
> match!(T,
> int, () => i = value,
> string, () => s = value
> );
> }
>
> test(1);
> test("A string");
>
> The compiler complains about not being able convert an int to a
> string and vice versa.
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.
More information about the Digitalmars-d-learn
mailing list