Wrong enum comparisons

bearophile bearophileHUGS at lycos.com
Mon May 28 08:16:29 PDT 2012


Andrei Alexandrescu:

> I do agree that it's wrong to _conflate_ the enumerated value 
> with it ordinal, so in this program neither comparison should 
> compile without an explicit cast:
>
> enum E1 { A, B }
> enum E2 { C, D }
>
> void main() {
>     E1 a;
>     assert(a == 0);
>     assert(a == E2.C);
> }
>
> The first one is probably difficult to disallow at this time,

I filed this first problem in 2010-03 (I have not filed the 
Enum1==Enum2 problem yet):
http://d.puremagic.com/issues/show_bug.cgi?id=3999

This is a small breaking change, but it doesn't introduce bugs in 
already written code, it turns into compile-time errors code that 
currently compiles. I think the usual way to solve this 
compile-time error is to use a cast (or sometimes use this safe 
to!() enhancement: 
http://d.puremagic.com/issues/show_bug.cgi?id=8143 ).


C++11 has "solved" this compatibility problem creating another 
kind of enum, referred as "enum class":

enum class Foo { V1 = 10 };
int main() {
     int b = Foo::V1 == 10;
}


test.cpp: In function 'int main()':
test.cpp:3: error: no match for 'operator==' in '(Foo)10 == 10'
test.cpp:3: note: candidates are: operator==(int, int) <built-in>

The disadvantage of doing this is the complexity increase of the 
language.

I don't know how do you estimate how much difficult is to perform 
small breaking changes in the language.

Bye,
bearophile


More information about the Digitalmars-d mailing list