strong enums: why implicit conversion to basetype?

bearophile bearophileHUGS at lycos.com
Sun Jan 29 14:19:35 PST 2012


This is an important topic.

I have an enhancement requests on enums:
http://d.puremagic.com/issues/show_bug.cgi?id=3999
As usual language design is a matter of finding the right balance between strictness, that helps catch real bugs, and type "sloppiness" that makes code more handy, and avoids some casts that sometimes are themselves a source of bugs. C++11 has introduced enums with a stronger static typing compared to D enums. But it keeps the less strongly typed enum too. This increases C++11 language complexity, but allows the programmer to choose between strictness and flexibility at will.

Regarding flags management, I think D2 is not good enough about them. They are a common need for a system language and I think normal enums are not good enough for this specialized purpose. Normal enums are both not handy enough and not safe enough for this purpose.
So an idea is to introduce something like a "@flags enum". But I think a library solution is enough here, just like bitfields. I have written this:
http://d.puremagic.com/issues/show_bug.cgi?id=6946
A problem with this implementation is that needs operator overload (with preconditions) to catch some wrong usages. Another problem is that is doesn't allow to add flag combinations inside the flag list itself. Maybe if you try to solve this second problem you increase too much the complexity of this implementation, so I have left them out.

In this thread I have seen various library solutions to implement flags. I think Andrei will be glad to add to Phobos a flags library solution that combines the best ideas of the various implementations.

Bye,
bearophile


More information about the Digitalmars-d mailing list