strong enums: why implicit conversion to basetype?

Chad J chadjoan at __spam.is.bad__gmail.com
Fri Jan 27 04:34:06 PST 2012


On 01/26/2012 08:17 PM, Simen Kjærås wrote:
> On Thu, 26 Jan 2012 23:49:40 +0100, Alvaro <alvaroDotSegura at gmail.com>
> wrote:
>
>> El 26/01/2012 14:59, Trass3r escribió:
>>> I thought it'd be good to outsource this question from the other thread
>>> about enums as flags.
>>>
>>> Is there any merit in having implicit conversion to the basetype?
>>> Imo it only introduces a severe bug source and brings no advantages.
>>
>>> A better example is something like
>>> if (b && Bla.S2) // written '&&' instead of '&' by mistake, will
>>> silently pass
>>> Heck even +,-,... work.
>>
>> I kind of agree. I understand enums as a way to define "tags" or flags
>> used to define things like file open mode Read, Write, ReadWrite,
>> endianness BigEndian, LittleEndian, socket type Stream/Packet, etc.
>> things that under the hood are represented by integer numbers but that
>> don't represent *quantities*, so should not work the same way as
>> integers. What is the result of subtracting or multiplying
>> LittleEndian and BigEndian? Does not make sense. Bitwise operations
>> would be OK because logica tags can be combined, but little more.
>
> Sometimes, bitwise operations make sense, other times not. Enums play two
> roles in D - that of an enumeration and that of a set of flags. Only for
> the latter do bitwise operations make sense.

You'd think that with some use of a templated struct and some "alias 
this" we'd be able to have a strongly-typed type for storing sets of 
flags.  It could even offer convenience functions like "getFlag" and 
"setFlag" to make the code read a bit nicer.


More information about the Digitalmars-d mailing list