Setting up a final switch from a list

Salih Dincer salihdb at hotmail.com
Thu Mar 28 22:21:03 UTC 2024


On Thursday, 10 August 2023 at 08:33:13 UTC, Christian Köstlin 
wrote:
> I think one part of the original question (now fanished in the 
> nntp backup) was how to get all enum members into a list 
> without duplicating code.
>
>
> ```d
> import std.traits : EnumMembers;
> import std.stdio : writeln;
> import std.algorithm : map;
> import std.conv : to;
> enum alphabet {
>   a, b, c, d
> }
>
> void main()
> {
>   writeln(EnumMembers!alphabet);
>   writeln([EnumMembers!alphabet]);
>   writeln([EnumMembers!alphabet].map!(a => "test" 
> ~a.to!string));
> }
> ```
>
> results in
>
> ```d
> abcd
> [a, b, c, d]
> ["testa", "testb", "testc", "testd"]```
> ```

How can we add all members of an enum type to a list without 
duplicating code?

I wonder if this is something we'll see soon as the D language 
feature?

In the D programming language, this can be achieved using 
features provided by the language such as __traits and AliasSeq. 
For instance, the EnumMembers trait from the std.traits module 
returns all members of an enum type as a tuple. This tuple 
contains the enum members in sequence, allowing for iteration 
over them or conversion into a list.

Finally, utilizing these language features to avoid code 
duplication and write cleaner, more maintainable code is a good 
practice. Sorry to resurrect this old thread, but what do you 
think; people living in 2024 ?

SDB at 79


More information about the Digitalmars-d-learn mailing list