Function-pointer valued enums
Steven Schveighoffer
schveiguy at gmail.com
Sat Jan 23 14:57:04 UTC 2021
On 1/22/21 7:21 PM, H. S. Teoh wrote:
> Amazingly, it works! Did you know that in D, enums can be
> function-pointer-valued? :-D
>
> Now all I have to do to add a new metric is to write the function, then
> add the function pointer to the enum, and it automagically learns how to
> parse the new option!
>
> One last thing remained: if the user didn't know what metrics were
> available, I'd like to supply a list. Being a lazy D metaprogrammer,
> I'm certainly not gonna manually type out the list and then have to
> maintain it every time I change the list of metrics. So compile-time
> introspection comes to the rescue:
>
> enum ident(alias Memb) = __traits(identifier, Memb);
>
> void showHelp() {
> ...
> alias T = Metric;
> ...
> alias membs = EnumMembers!T;
> immutable string[membs.length] membNames = [
> staticMap!(ident, membs)
> ];
> stderr.writefln("Available metrics: %-(%s, %)", membNames);
> ...
> }
>
> And with that, the act of adding a new function pointer to Metric
> automatically adds it to the displayed list of available metrics with no
> extra effort from me.
Cool idea! I like the fact that only "approved" functions are available
(though you can cast to add your own).
I think that any type that can implicitly be used as an integer can be
used as an switch type (apparently including pointers).
And then there's strings, which generate a specialized translation into
an integer (and this requires compiler help, because the strings are
sorted by length first). Then the switch is run on that integer.
Potentially, one could instrument ANY type with compiler help to be
usable in switch with something like opSwitchSort (run at CTFE to
generate the case orderings), and opSwitchTranslate (run when you switch
on a value).
-Steve
More information about the Digitalmars-d
mailing list