Wrong enum comparisons

foobar foo at bar.com
Mon May 28 06:19:41 PDT 2012


On Monday, 28 May 2012 at 08:58:29 UTC, Denis Shelomovskij wrote:
> 27.05.2012 23:45, bearophile написал:
>> In some code I have created a small bug that can be reduced to 
>> something
>> like this, that the D compiler has not caught at compile-time:
>>
>>
>> enum E1 { A, B }
>> enum E2 { C, D }
>> void main() {
>> E1[2] a;
>> with (E2)
>> assert(a[0] == D);
>> }
>>
>>
>> Why isn't D able to statically tell when you compare values of 
>> different
>> enums?
>> How much work is implementing this compile-time test inside 
>> the D
>> front-end?
>>
>> Thank you,
>> bye,
>> bearophile
>
> Enumerations are in very poor state in D now. May be, it should 
> be deprecated just like typedef and be library-implemented. 
> Why? Because we do need really strict type/operation checking 
> with enum so one have to write explicitly casts to do 
> non-standard things. The two main enumeration types are:
>  * list - must hold only one value, only opAssign and opEqual 
> are allowed, by default nextValue = prevValue + 1 starting with 
> 0
>  * flags - must hold superposition of values, like list, but 
> binary operations are also allowed, by default nextValue = 
> prevValue << 1 starting with 1
>
> These also allow finally implement right to!string for flags.
>
> By the way, current enums can be modified to correspond "list" 
> enumeration and flags can be added as library component.

I have to loudly object to this definition. Given a typical 
enumeration such as:
enum color {Blue, Green, Red};
Who's to say that Blue must equal 0? This is conceptually plain 
*wrong*.

A conceptually correct enumeration must NOT expose such 
implementation details as the very poor C/D style enums do. See 
functional languages such as ML for a correct implementation and 
also Java 5 Enums (similar but with an OO flavor).

The second point is conceptually *wrong* as well - a set of flag 
values is exactly that - _a set_. The type-safe correct way is to 
use a set!MyEnum to properly represent this (of course with a 
specialized implementation for this using bits for performance 
reasons).


More information about the Digitalmars-d mailing list