Mixin replacement for switch...case?
Philippe Sigaud
philippe.sigaud at gmail.com
Wed Oct 24 11:22:21 PDT 2012
Damn, I typed this a bit too fast. I forgot the imports:
> Probably, but my solution can be generalized further, to provide a
> sort of pattern-matching:
Add:
import std.conv;
import std.stdio;
> template match(cases...)
> {
> auto match(Input...)(Input input)
> {
> static if (cases.length == 0)
> static assert(false, "No match for args of type "~ Input.stringof);
> else static if (__traits(compiles, cases[0](input))) // Can we
> call cases[0] on input?
> return cases[0](input); // If yes, do it
> else // else, recurse farther down
> return .match1!(cases[1..$])(input);
> }
> }
>
> string more(T...)(T t){ return "More than two args. Isn't life wonderful?";}
>
>
>
> void main()
> {
> alias match!(
> () => "No args",
> (a) => "One arg, of type " ~ typeof(a).stringof ~ " with
> value: " ~ to!string(a),
> (a, string b)=> "Two args (" ~ to!string(a) ~ ", " ~
> to!string(b) ~ "). I know the second one is a string.",
> (a, b) => "Two args",
> more
> ) matcher;
>
> writeln(matcher());
> writeln(matcher(3.1416));
> writeln(matcher(1, "abc"));
> writeln(matcher(1, 1));
> writeln(matcher(1, "abc", 3.1416));
> writeln(matcher(1,1,1,1,1));
> }
More information about the Digitalmars-d
mailing list