On Saturday, 19 March 2016 at 17:41:29 UTC, Lass Safin wrote:
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?

Meant "Can also be cast(Derived) instead."

"enum B : A" doesn't mean "B extends A", but rather "enum B containing members of type A". Not specifying a type makes it implicitly convertible to int, I think.

If you're looking to extend a named enum, I think you have to create a new one. It will become a new type too, though that might not matter.

enum Foo { first=123, second=456, third=789 } // int type inferred

enum Bar : int {  // the ": int" here is important
    first  = Foo.first,  // implicit cast to int
    second = Foo.second,
    third  = Foo.third,
    fourth = 42,
    fifth  = 0
}

If you don't define Bar as having members of type int, it will guess that you want Foo (because we're assigning members with values of Foo's). They would be limited to the range of values Foo offers, and Bar.fourth = 42 is irreconcilabe with that.

Reply via email to