DIPX: Enum Literals / Implicit Selector Expression

ryuukk_ ryuukk.dev at gmail.com
Thu Jun 30 10:51:31 UTC 2022


On Thursday, 30 June 2022 at 09:19:15 UTC, bauss wrote:
> On Thursday, 30 June 2022 at 09:08:30 UTC, Ogi wrote:
>> ... But for some reason it’s not the case with enums. ...
>
> ```d
> enum Color { red, orange = 3 }
>
> int orange = 1;
>
> Color color = orange;
> // what is color?
> // or what about
> auto color = orange;
> // What is color?
> // or this:
> auto color = cast(int)orange;
> // What is color?
> ```
>
> Arguably each of these can be defined behavior and can be 
> solved, but what defined behavior is correct depends entirely 
> on what people expect to be true, and that's very different 
> depending on the type of project(s) people work on, what 
> language background they come from etc.
>
> For me the first one will be 1, because I believe a defined 
> value should override an enum value if specified, but this may 
> be different from others.
>
> The second one is the same, the type should be int and not 
> Color.
>
> The third one has the type int as well and will obviously use 
> the int variable named orange in my expectation.
>
> However I can see the argument for other people wanting the 
> first one to be a compiler error because it's ambiguous, or 
> even that you cannot override enum values and thus it will take 
> the value from Color.
>
> All of these behavior are correct and neither is wrong, as it 
> all just depends on how one think about programming in terms of 
> types, values, rules etc.
>
> I don't think D could ever settle on a single rule here that a 
> majority would agree upon.

the goal is not to copy c/c++, it's to be smarter, they are not 
globals


> enum Color { red, orange = 3 }

> int orange = 1;


> Color color = orange;
> // what is color?


it's not ``.orange`` therefore it is your variable, it if were 
with the dot, it'd take what ever is in the enum


> auto color = orange;
> // What is color?

same, it's not ``.orange`` therefore it's 1, if it where with the 
dot, it's compile error telling you to be more explicit


> auto color = cast(int)orange;
> // What is color?


it's not ``.orange`` therefore it is your variable, it if were 
with the dot, it'd take what ever is in the enum, then apply the 
cast


I don't know it seems pretty obvious to me

This feature is too good to not have


More information about the Digitalmars-d mailing list