October 24, 2012 Re: Mixin replacement for switch...case? | ||||
---|---|---|---|---|
| ||||
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)); > } |
October 24, 2012 Re: Mixin replacement for switch...case? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jerome | On Wed, Oct 24, 2012 at 9:56 AM, Jerome <jerome.spamable@yahoo.com> wrote:
>> Remark 1: I understand that your mixin will be expanded into cascaded if...else statements. It would probably be more efficient to expand into switch...case, don't you think?
>
>
> Oh! I've just figured out that it is not a mixin, but a function template.
That was to allow runtime arguments to be used. In your example, value is a compile-time argument. In this case, all tests can be done at CT and your code should result *only* in the right branch: no need to develop an entire switch statement.
|
Copyright © 1999-2021 by the D Language Foundation