www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - an enum inside another enum

reply maarten van damme <maartenvd1994 gmail.com> writes:
Hi, would the response to this question :
http://stackoverflow.com/questions/757684/enum-inheritance be the same
for D?

I have these two enums:
enum first : string{
 a="a",
 b="b"
}

enum second : string{
 a=first.a,
 b=first.b,
 c="c"
}

Is there a way to make this cleaner? I don't mind having something like
second.firstchar.a
with firstchar  beeing a "first" enum.

To do that I would need to tell the enum that it can also use the type
"first" because in the end, that is a string too...
Jul 26 2012
next sibling parent Jacob Carlborg <doob me.com> writes:
On 2012-07-26 13:40, maarten van damme wrote:
 Hi, would the response to this question :
 http://stackoverflow.com/questions/757684/enum-inheritance be the same
 for D?

 I have these two enums:
 enum first : string{
   a="a",
   b="b"
 }

 enum second : string{
   a=first.a,
   b=first.b,
   c="c"
 }

 Is there a way to make this cleaner? I don't mind having something like
 second.firstchar.a
 with firstchar  beeing a "first" enum.

 To do that I would need to tell the enum that it can also use the type
 "first" because in the end, that is a string too...
I'm pretty sure it's possible to do with some meta programming magic. -- /Jacob Carlborg
Jul 26 2012
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
maarten van damme:

 enum first : string{
  a="a",
  b="b"
 }

 enum second : string{
  a=first.a,
  b=first.b,
  c="c"
 }

 Is there a way to make this cleaner?
By convention in D enum names start with an upper case. I have tried this, partially derived by Simen Kjaeraas code (with T.stringof), but isn't D supporting mixins inside enums? string EnumInh(T)() if (is(T == enum)) { string result; foreach (e; __traits(allMembers, T)) result ~= e ~ " = " ~ T.stringof ~"." ~ e ~ ",\n"; return result; } enum First : string { a = "a", b = "b" } enum Second : string { mixin(EnumInh!First), c = "c" } void main() {} Bye, bearophile
Jul 26 2012
parent "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On Thu, 26 Jul 2012 15:07:56 +0200, bearophile <bearophileHUGS lycos.com>  
wrote:

 but isn't D supporting mixins inside enums?
Nope. "The text contents of the string must be compilable as a valid StatementList, and is compiled as such." And enums don't allow statements in their body. -- Simen
Jul 26 2012