enums and version/static if/"inheritance"

Witold Baryluk witold.baryluk+d at gmail.com
Wed Jul 31 00:52:52 UTC 2024


On Tuesday, 30 July 2024 at 19:32:45 UTC, Nick Treleaven wrote:
> On Monday, 29 July 2024 at 11:25:45 UTC, Nick Treleaven wrote:
>> Possible workaround if each enum member is given a specific 
>> initializer:
>> ```d
>> struct FooEnum
>> {
>>     int A = 5, B = 6;
>>     version (x86_64) {
>>         int C = 7;
>>     } else version (AArch64) {
>>         int C = 17;
>>     } else {
>>         static assert(0);
>>     }
>> }
>>
>> mixin enumGen!(FooEnum, "FOO");
>
> Of course, the mixin there is not doing anything more than a 
> struct with enum members:
> ```d
> version = x86_64;
>
> struct FOO
> {
>     enum A = 5, B = 6;
>     version (x86_64) {
>         enum C = 7;
>     } else version (AArch64) {
>         enum C = 17;
>     } else {
>         static assert(0);
>     }
> }
>
> static assert(FOO.A == 5);
> static assert(FOO.B == 6);
>
> version (x86_64)
> static assert(FOO.C == 7);
> ```
>
> But potentially the mixin approach with int members could do 
> more - e.g. auto increment any int members without initializer 
> (i.e. whose value is zero), based on the previous lexical 
> member initializer.


The struct trick is pretty nice. I will give it a go. At least it 
should work for the time being.

I will try to type-safe it a bit more. I.e. so doing something 
like `Foo.A | Foo.B` results in some (compile time) constant with 
proper type and not bare int. So functions receiving these enums 
can properly detect pass of naked integers, and such.

This has a potential.



More information about the Digitalmars-d mailing list