www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Inherit enum members

reply Andrey <saasecondbox yandex.ru> writes:
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 Key
How to understand this?
Apr 21 2019
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
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 type
 enum ExtendedKey : Key
So 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.
Apr 21 2019
prev sibling parent Alex <AJ gmail.com> writes:
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?
 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 Key
How to understand this?
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.
Apr 21 2019