How to correctly generate enums at compile time.

Kevin Balbas via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Apr 30 13:05:59 PDT 2017


I've got the following code snippet, which almost does what I 
want.

struct TaggedType {}

@TaggedType
struct Foo {}

@TaggedType
struct Bar {}

string GenerateTypeEnum()
{
     string enumString = "enum TypeEnum {";
     foreach (name; __traits(allMembers, mixin(__MODULE__)))
     {
         import std.traits;
         static if (hasUDA!(mixin(name), TaggedType))
         {
             enumString ~= name;
             enumString ~= "Type,";
         }
     }
     enumString ~= "}";
     return enumString;
}

// generates enum TypeEnum {FooType,BarType,}
mixin(GenerateTypeEnum());

This works great, except that TypeEnum isn't accessible from 
other modules (undefined identifier 'TypeEnum'), which is kind of 
the point of doing this (I'm using the enum as a system-wide tag 
for inter-thread communication).  I can imagine why this would be 
the case, but it's a pretty serious problem.  Is there a way to 
do this?


More information about the Digitalmars-d-learn mailing list