Allow Conditional Compilation Inside Enum Declaration

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Apr 2 17:44:07 UTC 2024


On Saturday, March 30, 2024 8:57:00 AM MDT IchorDev via dip.ideas 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,
>   }
> }
> ```

Yeah, I'm surprised by this every time that I run into it. I don't think
that I've ever tried it with static ifs, since usually, I run into it with
an enum where I need to change either the list of enum members and/or their
values based on the OS, so I'm trying to use version statements, but it
definitely comes up when writing code that has to worry about differences
between OSes. For instance, for a socket library, if you have an enum for
address families (e.g. inet, inet6, unix, etc.), that list is going to
differ depending on the OS.

Now, if the entire enum actually needs to only exist on a particular system,
then it makes sense that the whole thing would be versioned, but in the
cases where you need to change the list of members or their values based on
conditional compilation, it's definitely annoying that you're forced to
version the entire enum declaration.

I'm also pretty sure that this is the only place in the language where you
can put ddoc comments on individual symbols, but you can't use conditional
compilation for those symbols. It acts like a struct with regards to putting
ddoc on its members but then acts like an array literal with regards to
conditional compilation and its individual members / elements. So, it
definitely has inconsistent behavior with regards to other parts of the
language.

- Jonathan M Davis






More information about the dip.ideas mailing list