Generating enum members

cc us86kj+3rxcwe3ebdv7w at grr.la
Thu Mar 27 08:37:23 UTC 2025


On Saturday, 15 March 2025 at 14:47:01 UTC, Milli wrote:
> Hello everyone.
> It's my first time starting a thread here please have patience 
> and let me know if there is anything i have done wrong!
>
> I'm currently doing a project where there are two pretty 
> lengthy enums whose members depend on each other.
>
> Declaring one after the other makes it hard to double check 
> that i haven't missed anything, which is why i'm trying to make 
> a template mixin where i can declare the members together and 
> the template does all the appropriate sorting.
> I'm not having any luck in generating the enums though.
>
> The simplified version of what i need would be
> ```D
> mixin template create_enum(alias members) {
>   enum enumname {
>     static foreach(member; members) {
>       mixin(member.stringof,",");
>     }
>   }
> }
> ```
> which obviously doesn't work.
>
> Is it possible at all to do something like this in D?
>
> Thank you for the help!

If you have a 1:1 relationship between the enums, you could also 
declare one first as normal and then use templates/mixins to 
generate the second based on the first:
```d
enum FooA {
	RED = 1,
	GREEN = 2,
	BLUE = 4,
}
mixin(cloneEnum!(FooA, "FooB"));
string cloneEnum(E, string name)() {
	string s = "enum "~name~" {";
	foreach (member; EnumMembers!E) {
		s ~= format("%s = %s.%s,", member, E.stringof, member);
	}
	s ~= "}";
	return s;
}

void main() {
	assert(cast(int) FooA.BLUE == cast(int) FooB.BLUE);
}
```
And of course you can modify the function if you need any special 
logic to exclude or modify some members.


More information about the Digitalmars-d mailing list