Tuple enumeration without integers or strings
Paul Backus
snarwin at gmail.com
Sat Jan 2 03:20:29 UTC 2021
On Friday, 1 January 2021 at 23:14:43 UTC, Rekel wrote:
> I seem to have hit a bit of a wall when comparing D enums to
> Java enums.
> Of course the latter is just a fancy class, though it'd be nice
> to see partially equivalent usefulness regardless.
>
> For example, as soon as non-integer, non-string values are
> given to enums things get messy for me when using switch cases,
> I haven't yet found a satisfying way of doing this.
D's switch statement only works on strings and integers. For more
complex values, the easiest thing is to just use an if-else chain.
If you really want to use a switch statement, you can do it by
defining a function that maps each of your enum values to a
unique integer; for example:
enum Wind { ... }
size_t index(Wind w)
{
if (w = Wind.N) return 0;
// etc.
}
void someFunction(Wind w)
{
switch(w.index) {
case Wind.N.index: // uses CTFE
// ...
break;
// etc.
default: assert(0);
}
}
More information about the Digitalmars-d-learn
mailing list