enums

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 30 14:33:21 PDT 2014


Some explanation how the seemingly different concepts "enumerated 
value" and "manifest constant" are actually related:

Let's start with the "classical" enums as they're known from 
C/C++. They are used to create lists of symbolic names:

     enum Color { YELLOW, PINK, BLUE };

Internally, each of its members has an integer value by which it 
is represented. In the above example, YELLOW is 0, PINK is 1 and 
BLUE is 2. They are also implicitly convertible to their values. 
Whenever YELLOW, PINK or BLUE is used in the program, the 
compiler will treat it as if it were a literal 0, 1 or 2 (mostly; 
in some cases it is still possible to know that you're dealing 
with YELLOW instead of 0 by using introspection).

Normally, the compiler will assign values to the members starting 
from 0, but it's also possible to specify them explicitly:

     enum SIPrefixes { KILO = 1_000, MEGA = 1_000_000 };

An extension (and generalization) of this concept is to allow 
base types other than integers:

     enum WeekDays : string { MON = "Monday", TUE = "Tuesday" };

They, too, are implicitly convertible to their base types. And 
analogously to the Color enum, in this case the members are 
treated as if they were the string literals "Monday", or 
"Tuesday".

 From here, it's only a short distance to manifest constants. We 
can get there by making the braces optional when there is only 
one member and the enum type has no name, and allowing the base 
type to be automatically deduced:

     enum ManifestArrayLiteral = [1, 2, 3];

(I believe, internally DMD does treat the two concepts 
differently, but IMO this is a nice way to understanding how they 
work.)


More information about the Digitalmars-d-learn mailing list