an enum inside another enum

Simen Kjaeraas simen.kjaras at gmail.com
Thu Jul 26 04:59:07 PDT 2012


On Thu, 26 Jul 2012 13:40:06 +0200, maarten van damme  
<maartenvd1994 at gmail.com> wrote:

> 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?

string EnumDefAsString(T)() if (is(T == enum)) {
	string result = "";
	foreach (e; __traits(allMembers, T))
		result ~= e ~ " = T." ~ e ~ ",";
	return result;
}

template ExtendEnum(T, string s)
	if (is(T == enum) &&
	is(typeof({mixin("enum a{"~s~"}");})))
{
	mixin(
	"enum ExtendEnum {"
	~ EnumDefAsString!T() ~ s
	~ "}");
}

enum bar
{
	a = 1,
	b = 7,
	c = 19
}

import std.typetuple;

void main() {
//-----------------------
     alias ExtendEnum!(bar, q{ // Usage example here.
         d = 25
     }) bar2;
//-----------------------
     foreach (i, e; __traits(allMembers, bar2)) {
         static assert( e == TypeTuple!("a", "b", "c", "d")[i] );
     }
     assert( bar2.a == bar.a );
     assert( bar2.b == bar.b );
     assert( bar2.c == bar.c );
     assert( bar2.d == 25 );
     static assert(!is(typeof( ExtendEnum!(int, "a"))));
     static assert(!is(typeof( ExtendEnum!(bar, "25"))));
}

-- 
Simen


More information about the Digitalmars-d-learn mailing list