boilerplate for constructor
Timothee Cour via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 10 23:16:06 PDT 2015
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");
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150310/89993c69/attachment.html>
More information about the Digitalmars-d-learn
mailing list