semi-final switch?

jfondren julian.fondren at gmail.com
Fri Jun 18 05:05:31 UTC 2021


On Friday, 18 June 2021 at 04:24:19 UTC, jfondren wrote:
> On Thursday, 17 June 2021 at 21:41:28 UTC, Steven Schveighoffer 
> wrote:
>> A final switch on an enum complains if you don't handle all 
>> the enum's cases. I like this feature.
> ...
>> Oh, and to throw a monkey wrench in here, the value is a 
>> string, not an integer. So I can't use std.conv.to to verify 
>> the enum is valid (plus, then I'm running a switch twice).
>
> Wanting to avoid more work than a switch means generating a 
> switch.
> I think that's the real monkey wrench.
>

Alternately, weave the check you want into your switch:

```d
import std.traits : EnumMembers;
import std.algorithm : map, canFind;
import std.conv : to;

enum C { ABC, XYZ }

alias namesEnum(E) = s => 
[EnumMembers!E].map!(to!string).canFind(s);
enum enumCount(E) = [EnumMembers!E].length;

int example(string k) {
     switch (k) {
         case "ABC": static assert("ABC".namesEnum!C);
             return 1;
         case "XYZ": static assert("XYZ".namesEnum!C);
             return 2;
         default: static assert(2 == enumCount!C);
             return 0;
     }
}

unittest {
     example("force asserts");
}
```

but this repeats the keys (which could be mis-repeated), and it
requires hand-counting the cases checked (which could be 
mis-counted).
At least it's easier to check without reference to the enum.

What I wanted to do was add "ABC"&c to a static string[] and
confirm that it's a permutation of 
[EnumMembers!C].map!(to!string).


More information about the Digitalmars-d-learn mailing list