digitalmars.D.learn - Inherit enum members
- Andrey (4/22) Apr 21 2019 Result:
- Adam D. Ruppe (20/22) Apr 21 2019 You don't. enums don't inherit, but rather have a base type. That
- Alex (11/33) Apr 21 2019 I don't know why you want to do this, just use string directly.
Hello, I have got 2 enums. How to inherit one enum from another?enum Key : string { K1 = "qwerty", K2 = "asdfgh" } enum ExtendedKey : Key { E1 = "q1", E2 = "w2", E3 = "e3" }Result:onlineapp.d(27): Error: cannot implicitly convert expression "q1" of type string to Key onlineapp.d(28): Error: cannot implicitly convert expression "w2" of type string to Key onlineapp.d(29): Error: cannot implicitly convert expression "e3" of type string to KeyHow to understand this?
Apr 21 2019
On Sunday, 21 April 2019 at 20:58:19 UTC, Andrey wrote:I have got 2 enums. How to inherit one enum from another?You don't. enums don't inherit, but rather have a base type. That means each enum member must match that base type and the compiler is looser about conversions between them, but they do not inherit members. enum Key { // no base type K1, K2 } int a = Key.K1; // not allowed enum Key : int { // base type if int K1 = 0, K2 = 1, } int a = Key.K1; // allowed, because of same base typeSo this would be defining an enum with base type of Key... meaning each member of it must be of type Key. But Key's members are NOT carried over. As far as I know, the language does not permit what you want. You'll have to copy over any matching members yourself.enum ExtendedKey : Key
Apr 21 2019
On Sunday, 21 April 2019 at 20:58:19 UTC, Andrey wrote:Hello, I have got 2 enums. How to inherit one enum from another?I don't know why you want to do this, just use string directly. enum ExtendedKey : typeof(EnumMembers!Key[0]) { q = EnumMembers!Key[0] } would work.. Alternatively look at this thread: https://forum.dlang.org/thread/irvtrixunermburvviib forum.dlang.org?page=2 Where you can use the code and classes to subtype and emulate enums.enum Key : string { K1 = "qwerty", K2 = "asdfgh" } enum ExtendedKey : Key { E1 = "q1", E2 = "w2", E3 = "e3" }Result:onlineapp.d(27): Error: cannot implicitly convert expression "q1" of type string to Key onlineapp.d(28): Error: cannot implicitly convert expression "w2" of type string to Key onlineapp.d(29): Error: cannot implicitly convert expression "e3" of type string to KeyHow to understand this?
Apr 21 2019