bit-level logic operations on enums

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 1 16:36:19 PST 2013


On Fri, 01 Mar 2013 19:22:14 -0500, Era Scarecrow <rtcvb32 at yahoo.com>  
wrote:

> On Friday, 1 March 2013 at 23:00:58 UTC, Steven Schveighoffer wrote:
>> I was sure too.  It's not.  Any operation between A types results in A.
>>
>> writeln(typeof(a + a).stringof); // => A
>> writeln(typeof(a << a).stringof); // => A
>> writeln(typeof(a * a).stringof); // => A
>
>   It has to be a bug, as it doesn't make sense for it to be legal.

Read the spec, carefully.  It's implemented as designed.

http://dlang.org/type.html

Implicit conversion: "A enum can be implicitly converted to its base type,  
but going the other way requires an explicit conversion."

But for integer promotion:

"If a enum has as a base type one of the types in the left column, it is  
converted to the type in the right column."

The left column referred to does not have anything 32-bit or above in it  
besides dchar.  Remember that.

Later on, regarding arithmetic operations:

If one or both of the operand types is an enum after undergoing the  
[Integer promotion] conversions, the result type is:
* If the operands are the same type, the result will be the (sic) that  
type.
* If one operand is an enum and the other is the base type of that enum,  
the result is the base type.
* If the two operands are different enums, the result is the closest base  
type common to both. A base type being closer means there is a shorter  
sequence of conversions to base type to get there from the original type.

Note that if no integer promotion occurs (i.e. base type is 32 bits or  
above and not dchar), and you are adding A with A, both operands are of  
the same type, so "the result will be that type."

Just bad design IMO.  It should be fixed.

-Steve


More information about the Digitalmars-d mailing list