enum

Jonathan M Davis jmdavisProg at gmx.com
Sat Apr 12 05:59:29 PDT 2014


On Friday, April 11, 2014 19:52:58 Andrei Alexandrescu wrote:
> On 4/11/14, 6:59 PM, Jonathan M Davis wrote:
> > On Friday, April 11, 2014 17:01:15 Andrei Alexandrescu wrote:
> >> On 4/11/14, 12:31 PM, Jonathan M Davis wrote:
> >>> On Friday, April 11, 2014 08:22:01 Steven Schveighoffer wrote:
> >>>> final enum name { ... }
> >>> 
> >>> This only makes sense to me if it's then illegal to declare any
> >>> variables
> >>> of that enum type, because if you're looking to use an enum to give a
> >>> list of possible values rather than enumerating the exact list of
> >>> values,
> >>> why would you be marking _any_ variable as being of that enum type?
> >> 
> >> I don't understand that contention. "final" clarifies that the set of
> >> values in the enumeration is closed.
> > 
> > I take issue with the idea that it makes sense to have any variables of an
> > enum type that isn't one of the values enumerated in the enum.
> 
> I explained the possible situations in the original post of this thread.
> E.g. one may be unable to enumerate all user IDs, but may be compelled
> to enumerate a few remarkable ones and ascribe user IDs a separate type.
> -- Andrei

And what would the purpose by of giving them their own type? If the enum 
doesn't enumerate all of the values, then you're clearly going to be using 
other values with it, meaning that any restrictions on setting a variable to 
those other values is going to be a problem (as is currently the case with 
enums - assignment and initialization are protected against non-enumerated 
values). You'd just end up with a enum type which is effectively an alias for 
the enum's base type except that assigning it non-enumerated values requires 
casting, and you can overload a function on the enumerated values vs the non-
enumerated ones (or at  least, non-enumerated ones which aren't cast to the 
enum type) by overloading a function on the enum type and its base type - 
which would be highly bug-prone IMHO.

In such a case, the enum type is adding nothing but a name, so why not just 
use an alias - especially when even the minimal protections that enum types 
currently have against other values will get in the way of using it for non-
enumerated values. And that would be particularly painful in your example, 
because the enum only had UserID.nobody and UserID.expired, meaning that 
nearly ever time you initialized or assigned to a UserID, you'd have to cast. 
It sounds like what you really want/need is an alias along with an enum with 
the constants for nobody and expired, but given how enums work even now 
(without the full protections that I think they should have), actually using 
the enum type for user IDs is just going to cause problems.

- Jonathan M Davis


More information about the Digitalmars-d mailing list