digitalmars.D.learn - boilerplate for constructor
- Timothee Cour via Digitalmars-d-learn (37/37) Mar 10 2015 I'm trying to define a boilerplate mixin for class constructor to genera...
I'm trying to define a boilerplate mixin for class constructor to generate code such as: this(T1 a1, T2 a2){this.a1=a1; this.a2=a2;} The following works, but fails if one field is from a superclass, with an error such as: template instance GenThis!(b, a) GenThis!(b, a) is nested in both B and A. Any suggestion? ---------- template GenThis(fields...){ import std.typecons; import std.typetuple; import std.conv; private static string fun(){ string a="this("; string b; foreach(i;Iota!(fields.length)) { alias field=fields[i]; auto name=Stringof!field; alias T=typeof(field); if(i>0) a~=", "; a~=T.stringof~" "~name; b~="this."~name~"="~name~"; "; } a~=`){`~b~`}`; return a; } enum GenThis=fun(); } unittest{ class A{ int foo; string bar; mixin(GenThis!(bar, foo)); } auto a=new A("abc",2); assert(a.foo==2 && a.bar=="abc"); }
Mar 10 2015