static code generation

Benjamin Thaut code at benjamin-thaut.de
Sun Dec 9 12:09:47 PST 2012


If you need a small example for code generation, the following code will 
generate code for translating any enum value into a string:

string EnumToStringGenerate(T,string templateVar = "T", string pre = 
"")(string var){
	string res = "final switch(" ~ var ~ "){";
	foreach(m;__traits(allMembers,T)){
		res ~= "case " ~ templateVar ~ "." ~ m ~ ": return \"" ~ pre ~ m ~ "\";";
	}
	res ~= "}";
	return res;
}

string EnumToString(T)(T value){
	mixin(EnumToStringGenerate!(T)("value"));
}

Example usage:

enum Test
{
   Value1,
   Value2
}

writefln(EnumToString(Test.Value1)); //Will print "Value1"

Kind Regards
Benjamin Thaut


More information about the Digitalmars-d-learn mailing list