enum with classes/structs

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 10 11:26:56 PST 2011


On Thursday, March 10, 2011 11:15:25 useo wrote:
> Hey guys,
> 
> is it possible to declare a enum where all entries are instances of a
> class (or struct), like the following:
> 
> class a {
>    ...
>    public this(uint i) {
>      ...
>    }
>    ...
> }
> 
> enum myEnum : a {
>    entry1 = new a(0);
>    entry2 = new a(1);
> }
> 
> ... or does enumerations only support constant-expressions? Thanks!

enums _definitely_ only support constants. However, anything which is doable with 
CTFE should work with an enum as long as the result is const or immutable (or 
convertible to const or immutable). So, it _should_ be possible to have an enum 
where all of its values are structs. And something like this works:

struct S
{
    ...
}

enum val = S(24);

However, for some reason, having an enum of a struct type with multiple values 
doesn't currenty work (I believe that it relates to comparison - when you have 
multiple values in an enum, they have to be comparable, because they're 
ordered):

http://d.puremagic.com/issues/show_bug.cgi?id=4423

Classes do not currently work with CTFE, so they _definitely_ don't work. 
However, the goal is that eventually everything which is legal in SafeD will 
work with CTFE, and if/when we reach that point, then it would be legal to have 
an enum of class objects. However, _regardless_ of the type of an enum, its 
values can't be changed, so even if you had a struct or class object as an enum 
value, you wouldn't be able to change its value or call any non-const functions 
on it.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list