Generating enum members

H. S. Teoh hsteoh at qfbox.info
Sat Mar 15 15:08:06 UTC 2025


On Sat, Mar 15, 2025 at 02:47:01PM +0000, Milli via Digitalmars-d wrote:
[...]
> 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?
[...]

Of course it's possible.  D is the king of meta-programming, and
something like this is right up its alley.

What you want is a string mixin + CTFE:

	string create_enum(string[] members) {
		string code = "enum MyEnum { ";
		foreach (memb; members) {
			code ~= memb ~ ", ";
		}
		code ~= "}";
		return code;
	}

	mixin(create_enum([ "memb1", "memb2", "memb3" ]);


T

-- 
Knowledge is that area of ignorance that we arrange and classify. -- Ambrose Bierce


More information about the Digitalmars-d mailing list