Enum literals, good? bad? what do you think?

claptrap clap at trap.com
Tue Jul 20 21:52:45 UTC 2021


On Tuesday, 20 July 2021 at 21:15:19 UTC, Ali Çehreli wrote:
> On 7/20/21 1:43 PM, claptrap wrote:
>
> > So if you have a function...
> >
> > void handleError(OtherResult r);
> >
> > and call it thus...
> >
> > handleError(OK);
> >
> > You know it's OtherResult.OK
> >
> > Isnt that the point of strong typing?
>
> Most of the time yes, but our enums are not that strong. :) The 
> following compiles and runs with both types.
>
> enum Animal { Jaguar = 100 }
> enum Car    { Jaguar = 42 }
>
> void foo(int i) {
> }
>
> void main() {
>   foo(Animal.Jaguar);
>   foo(Car.Jaguar);
> }
>
> But the your argument will probably be
>
>   foo(Jaguar);

That that would be an error since the parameter is an 'int' so 
you dont have any context to decide what enum it should refer to. 
IE..

void foo(int i);
void bar(Animal a);

foo(Animal.Jaguar); // OK
foo(Jaguar); // Error
bar(Jaguar); // OK

likewise

auto a = Jaguar; // Error
Car c = Jaguar; // OK

The point is you should only be able to drop the enum name if the 
parameter or the variable you're assigning to are ***named 
enums***. I suppose for switch you could do the same, if the 
variable being switched on is a named enum, then the cases can 
drop the name.




More information about the Digitalmars-d mailing list