enums and version/static if/"inheritance"

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


On Tuesday, 30 July 2024 at 23:26:58 UTC, IchorDev wrote:
> I’ve recently made a API for doing this in BindBC-Common. You 
> can see it on the latest commit of my repository 
> [here](https://github.com/BindBC/bindbc-common/blob/f9b30591e05238fcda80bb6b070acacd1f77f018/source/bindbc/common/codegen.d#L500). This is not tagged as a version yet, but you can download it & use `dub add-local` until I tag it.
>
> It’s designed for making language bindings (mostly to C) so 
> there’s a convenient way to have a D version of the enum (e.g. 
> `Plant.flower`) and a C version (e.g. `PLANT_FLOWER`) with the 
> same code. And you can turn them on and off easily so that 
> people who don’t like one of the styles are still happy.
> Usage is like…
> ```d
> import bindbc.common;
>
> mixin(makeEnumBindFns(cStyle: true, dStyle: true)); //this 
> defines `makeEnumBind`
>
> //makes `enum Plant: ulong`:
> mixin(makeEnumBind(q{Plant}, q{ulong}, members: (){
>   EnumMember[] ret = [
>     {{q{flower}, q{PLANT_FLOWER}}, q{1}},
>     {{q{bush},   q{PLANT_BUSH}},   q{2}},
>   ];
>   if(condition){
>     EnumMember[] add = [
>       {{q{herb},   q{PLANT_HERB}},   q{4}},
>     ];
>     ret ~= add;
>   }
>   return ret;
> }()));
> ```
> Please note that some parameters and fields are **required** to 
> be referred to by name. Read the documentation comments for 
> `makeEnumBind`, `EnumMember`, and `EnumIden` to avoid misusing 
> them.


All nice and dandy. I know how to write mixins, there are many 
ways to do it. I am just surprised language feature of `version` 
and `static if` that work so easily in many other places, cannot 
be used for anything useful in enums and enums only.

Is it really like so rare that it is not in the language?

Usually one would not want to define an enum that have different 
values and enum members, as this can mess other code. But then it 
is pretty normal when interfacing with other languages and 
systems, or even doing things like changing some default values 
depending on a version.

Phobos (especially core and sys and stdc) with free standing 
enums, partially due to this problem.



I do like idea of the struct with static enum members. It might 
just work, without CTFEs and mixins. I will give it a try.



More information about the Digitalmars-d mailing list