Enum literals, good? bad? what do you think?
Walter Bright
newshound2 at digitalmars.com
Wed Jul 21 06:39:18 UTC 2021
On 7/20/2021 9:12 AM, H. S. Teoh wrote:
> OTOH, I agree that sometimes D enums become rather verbose. Especially
> in switch statements where you have to repeat their name for every case.
> Fortunately, this is where D's `with` statement comes in helpful:
>
> enum MyEnum { blah, bleh, bluh }
> MyEnum val = ...;
> final switch (val) {
> case MyEnum.blah: ...
> case MyEnum.bleh: ...
> case MyEnum.bluh: ...
> }
In C, qualifying the member name with the tag name is not only not necessary, it
is not allowed. Hence, here how C does it:
enum MyEnum { MyEnum_blah, MyEnum_bleh, MyEnum_bluh };
enum MyEnum val = ...;
switch (val) {
case MyEnum_blah: ...
case MyEnum_bleh: ...
case MyEnum_bluh: ...
}
It's not very attractive. C++ eventually added some more syntax so the members
had to be qualified. This is because once the project exceeds a certain level of
complexity, qualifying those enum member names becomes desirable.
But if you still want unqualified names, `alias` is the feature:
enum MyEnum { blah, bleh, bluh }
alias blah = MyEnum.blah;
alias bleh = MyEnum.bleh;
alias bluh = MyEnum.bluh;
`alias` is an all-purpose tool for moving names from one scope to another. Of
course, one can probably do a mixin to automate the alias declarations. It
should be a fun exercise. Any takers?
(As mentioned by others, `with` does it too, but `with` only affects the scope
it specifies.)
More information about the Digitalmars-d
mailing list