On Wednesday, 2 March 2016 at 14:50:15 UTC, Adrian Matoga wrote:
On Wednesday, 2 March 2016 at 14:36:59 UTC, Daniel Kozak wrote:
OK maybe this one:
template AddField(T) {
T b;
this(Args...)(T b, auto ref Args args)
{
this.b = b;
this(args);
}
this(int a) {
this.a = a;
}
}
struct Bar {
int a;
mixin AddField!(string);
}
unittest {
auto bar1 = Bar(5);
auto bar2 = Bar("bar", 15);
}
Then it's limited to structs in which only "int a" is to be
initialized. Not very useful and the templated ctor is not
needed now.
struct Baz {
mixin AddField!string; // fail, no "int a" in Baz.
ulong d;
double x;
string foo;
}
OK then:
mixin template AddField(T) {
T b;
auto ref constructor(Args...)(T b, auto ref Args args)
{
typeof(this) r;
r.b = b;
r.__ctor(args);
return r;
}
}
struct Bar {
mixin AddField!string;
int a;
this(int a) { this.a = a; }
alias __ctor = constructor;
}
unittest {
import std.stdio;
auto bar1 = Bar(5);
auto bar2 = Bar("bar", 15);
writeln(bar1);
writeln(bar2);
}