enum with classes/structs

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 10 11:37:16 PST 2011


On Thursday, March 10, 2011 11:28:04 bearophile wrote:
> useo:
> > is it possible to declare a enum where all entries are instances of a
> 
> > class (or struct), like the following:
> I don't think so. Enums are compile-time constants.
> This code doesn't compile:
> 
> class A {
>    this(uint i) {}
> }
> enum myEnum : A {
>    entry1 = new A(0),
>    entry2 = new A(1)
> }
> void main() {}
> 
> It's important to understand that in D OOP and procedural/C-style features
> are often separated. typedef didn't work well with OOP. Don't mix things
> that are not meant to be mixed.

There's absolutely nothing wrong with mixing enum with OOP. An enum is simply an 
enumeration of values. There's absolutely nothing wrong with those values being 
of struct or class types. The only restrictions there are problems with the 
implementation. TDPL even gives examples of enum structs. They currently work 
when you only have one value in the enum, but fail when you have multiple ( 
http://d.puremagic.com/issues/show_bug.cgi?id=4423 ). If/When classes work with 
CTFE, then you should be able to haveenums of class objects.

There's nothing about enums which are C or procedural-specific. Java has object-
oriented enums which are quite powerful. And aside from the current 
implementation issues, D's enums are even more powerful because they allow _any_ 
type and so can be either primitive types or user-defined types like you'd have 
in Java.

enums don't care one way or another about OOP. They're just a set of values that 
have to be ordered and be known at compile time.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list