Allow Conditional Compilation Inside Enum Declaration

Salih Dincer salihdb at hotmail.com
Tue Oct 15 12:39:46 UTC 2024


On Saturday, 30 March 2024 at 14:57:00 UTC, IchorDev wrote:
> To declare an enum type that may or may not have one or more 
> members depending on conditional compilation statements 
> requires duplicating the entire enum:
> ```d
> static if(cond){
> 	enum A{
> 		x,y,z,w,
> 	}
> }else{
> 	enum A{
> 		x,y,z,
> 	}
> }
> ```
>
> For an enum type with many members—or many conditionals—this 
> quickly becomes an insane amount of repetition.
>
> The logical solution is to just allow conditional compilation 
> statements inside enums:
> ```d
> enum A{
> 	x,y,z,
>     static if(cond){
> 		w,
> 	}
> }
> ```

I use a mixin generator for my types and I can switch between 2 
columns (different languages)/names with a static if. For example:

```d
struct ConsArray(Enum, size_t col)
{
   mixin(makeEnum!col);
   E[] list;
   size_t index;

   enum makeEnum(size_t mod) = () {
     size_t num;
     string str = "enum E {";
     static foreach(i, e; EnumMembers!Enum) {
       static if ((i & 1) ^ mod)
         str ~= e.format!"%s = %s,"(num++);
     }
     return str ~ "}";
   }();
//...
}

void main()
{
   enum Names
   { // mod 1, 0
         Andy, Ali,
        Cindy, Cengiz,
        Kenny, Kaan,
        Micky, Mehmet,
        Sunny, Salih
   }
   auto names = ConsArray!(Names, 1)();
   enum nameEn {Andy,Cindy,Kenny,Micky,Sunny}
}

```

If we wish, I could just give the enum directly with E without 
declaring a condition on my type. However this gives me 
error-free matching.

SDB at 79



More information about the dip.ideas mailing list