Allow Conditional Compilation Inside Enum Declaration

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


On Tuesday, April 2, 2024 11:30:39 AM MDT Basile B. via dip.ideas wrote:
> forgot to say you can use a struct filled with anonymous enum
> members too.
>
> ```d
> struct A
> {
>      enum T x = 0;
>      enum T y = 1;
>      enum T z = 2;
> static if (cond)
>      enum T w = 3;
> }
> ```
>
> However RN I cant confirm that the usage is 100% equivalent. Use
> of the members is likely but use of the container may not, e.g in
> std.traits (esp. the EnumMembers template ...).


They aren't equivalent at all, because you haven't declared any actual
enums. Even though the keyword enum is used, those are all manifest
constants within a struct, whereas an enum declaration declares its own type
which will be treated as an enum by the type system, and that affects a
number of things, including is experessions. For instance, is(A == enum)
would be false, and is(A == struct) would be true, whereas if it were an
enum declaration, the opposite would be true. Even if the enum's base type
were a struct is(E == struct) would still be false, because the enum itself
wouldn't be a struct. It would just implicitly convert to its base type
which was a struct.

Similarly, you can't use final switch with such a struct. You need an actual
enum.

You also couldn't do something like

    auto foo(A a) {...}

and pass it A.x, because x is a T, not an A.

Now, syntactically, such a struct is very similar to an enum declaration, so
you can do stuff like A.x, and it would be syntactically the same, but the
types would be different, and the way that the type system treats them would
be different.

So, depending on what you're doing, a struct with a bunch of manifest
constants might do the trick, but really, all you're doing is putting a
bunch of manifest constants within a namespace. You're not declaring an enum
type.

- Jonathan M Davis





More information about the dip.ideas mailing list