Thread overview
an enum inside another enum
Jul 26, 2012
maarten van damme
Jul 26, 2012
Jacob Carlborg
Jul 26, 2012
bearophile
Jul 26, 2012
Simen Kjaeraas
July 26, 2012
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...
July 26, 2012
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
July 26, 2012
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
July 26, 2012
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