On Saturday, 19 March 2016 at 17:40:27 UTC, Lass Safin wrote:
Why:

enum Base {
    A,
    B,
}

enum Derived : Base {
C, // Gives error, says it can't implicitly convert expression to Base.
    D = 1, // Same error
E = cast(Base)294, // Finally works. Can only be cast(Derived) instead.
}

void func(Derived d) {}

func(Derived.E); // works.
func(Derived.A); // Gives error, says it can't call function with Base.A.
func(cast(Derived)Derived.A); // Works.

So, what's the proper way of extending an enum?

There is no way to extend an enum. When you think about it, it's actually the opposite of what you'd generally want. Given two classes:

class A {}
class B : A {}

Every instance of B is a valid A. That is, given a variable of type A, you could assign any B to it.

Now consider enums:

enum A { x, y, z }
enum B : A {}

Which values could you put in B? Only those that would be valid for A. That is, only x, y and z. Imagine that we could:

enum B : A { w }

A foo = B.w;

foo now holds a value that is not valid for its type. Hence, you simply cannot.

Are there cases where you want to define a new enum that contains all the items in a 'base' enum in addition to some new items? Absolutely, and D lacks a good way to do that. But subtyping would in any case not be the correct way to do it.

Are there cases where you want to extend an enum by making a subtype with more items? I would argue that's a strong code smell in D, but I can see why you'd want to.

--
  Simen

Reply via email to