CTFE & enums & static assert

Robert M. Münch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 18 03:33:07 PDT 2015


On 2015-05-15 17:26:50 +0000, Ali Çehreli said:

> On 05/15/2015 09:45 AM, Robert M. Münch wrote:
> 
>  > Is there a way I can build an ENUM from within the FOREACH? What I want
>  > to achive is, that I would like to use:
>  >
>  > final switch (myEnum) ...
> 
> Sorry, I don't understand your question. :(
> 
> Do you want to define an enum at compile time? Then you can use mixins.
> 
> Do you want to build an enum value inside the foreach? Yes, it is 
> possible as well.

Hi, yes to both. I have solved it now like this:

enum A {a, b, c};
enum members1 = __traits(allMembers, A); // returns TypeTuple

// function that generates a string which is used as a mixin at compile time
// result string must conform to syntax as it was hand-written code
string generateEnum(T...)(string type){
    string code = "enum " ~ type ~ " {";

    // this is a static foreach (compile time)
    foreach(m; T){
      debug pragma(msg, m ~ ","); // check what code we get at compile time
      code ~= m ~ ",";
    }

    return(code ~ "}");
}

int main(){
    A switch_var_a;
    final switch(switch_var_a){
      case A.a:
      case A.b:
      case A.c:
    }

    mixin(generateEnums!members1("B"));
    B switch_var_b;
    final switch(switch_var_b){
      case B.a:
//      case B.b: // if commeted will cause a compiler error
      case B.c:
    }

    return(0);
}

So, the solution was to use a "string mixin".

IMO it's a very powerful pattern to build an ENUM at compile time that 
can be used with a FINAL SWITCH.

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster



More information about the Digitalmars-d-learn mailing list