enum
Jonathan M Davis
jmdavisProg at gmx.com
Thu Apr 10 22:29:09 PDT 2014
On Wednesday, April 09, 2014 21:47:42 Walter Bright wrote:
> On 4/9/2014 5:39 PM, Jonathan M Davis wrote:
> > On Wednesday, April 09, 2014 14:14:21 Andrei Alexandrescu wrote:
> >> One wants to call a function taking such an enum. -- Andrei
> >
> > But it _isn't_ going to be a valid enum value. IMHO, a function which is
> > taking or-ed flags where those flags are enums needs to take uint or ulong
> > or whatever the base type of the enum is and _not_ the enum type.
>
> It makes perfect sense if you think of an enum as an integral type, some
> values of which have names, as in the "Color" example I posted earlier.
If you can't reasonably rely on a variable of an enum type being on of the
enum's enumerated values, then final switch makes no sense whatsoever. Since
it has no default case, you'd have to first check that the value was a valid
enum value if you wanted the final switch to work to not hit the assert(0) or
whatever it is that happens when you give a final switch a value that it
doesn't have a case for.
For final switch to work correctly, you must be able to rely on variables of
an enum type being one of the values enumerated in the enum, which means that
the language should be restricting what you can set an enum variable's value
to to valid enum values (except when casting) - and it pretty much only does
that right now on direct assignment. It's trivial to append to an enum if
it's an array or do arithmetic on it if it's an arithmetic type. And that
means that it's trivial to break final switch.
In addition , there's plenty of existing code that won't work if you give it a
value that's not one of the enum's enumerated values - e.g. std.conv.to will
choke when trying to convert an enum value if it's not one of the enum's
enumerated values.
If you just want to give a list of values names, then you can use manifest
constants rather than an enumeration. IMHO, enumerations only make sense when
you're enumerating _all_ of the values for that enum. And if that's the case,
the language shouldn't allow enum variables to be set to invalid enum values
without casting. The current situation is highly bug-prone. And what you're
suggesting would require that most code that deals with enums protect itself
against being given enum values that weren't enumerated by the enum, which I'm
willing to bet pretty much no one does.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list