What is your favorite D feature? [Call for snippets]

Patrick Schluter via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 22 06:46:02 PDT 2017


On Thursday, 22 June 2017 at 07:00:17 UTC, Seb wrote:
>
> Thanks a lot, but I was looking for small snippets (< 10 LoC) 
> than could be used to show the awesomeness of D at the roulette


enum E {IN = -1, V1, V2, V3, X1 }

mixin({
   string code = "enum EBIT : ulong { "~
                         "init = 0,";      /* We set the dummy 
init value to 0 */
   foreach(Code; __traits(allMembers, E)) {
     static if(Code == "IN")
       code ~= "INVALID = -1,";
     else
       code ~= Code~"= 1 << E."~Code~",";
   }
   code ~= "
     ALL    =  -1,
   return code ~ "}";
}());

Generates an enum which values depend on the values of another 
enum.

In C or other languages I would needed to write the 2nd enum 
myself

enum EBIT { INVALID = -1,
              V1= 1 << E.V1,
              V2= 1 << E.V2,
              V3= 1 << E.V3,
              X1= 1 << E.X1,
           }

For a 4 value enum it doesn't look such a big deal but in my real 
project coming from C, the first enum holds more than 50 regular 
values and 3 special values. When I have to add or remove a value 
I have to edit the first enum, but also the 2nd enum, 5 derived 
lookup tables and 2 functions using a big switch/case with the 
enum values.
In D I edit only the first enum, the rest is auto-generated.

As 2nd trick/nice thing here is a function geenrating a 
switch/case with the enums.

string E2thing(E val)
{
   switch(val) {
     foreach(e; __traits(allMembers, E))
     static if(e != "IN")
       mixin(`case E.`~e~`: return "`~e~`";`);
     default: return "UNDEFINED";
   }
}




More information about the Digitalmars-d mailing list