Template mixins and struct constructors
Daniel Kozak via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Mar 2 04:48:47 PST 2016
On Wednesday, 2 March 2016 at 12:27:04 UTC, Adrian Matoga wrote:
> I can do this:
>
> struct Foo {
> int a;
> string b;
> this(int a) { this.a = a; }
> this(Args...)(string b, auto ref Args args) { this.b = b;
> this(args); }
> }
>
> unittest {
> auto foo1 = Foo(5);
> auto foo2 = Foo("foo", 15);
> }
>
> However, the following code is invalid:
>
> mixin template AddField(T) {
> T b;
> this(Args...)(T b, auto ref Args args)
> {
> this.b = b;
> this(args);
> }
> }
>
> struct Bar {
> mixin AddField!string;
> int a;
> this(int a) { this.a = a; }
> }
>
> unittest {
> auto bar1 = Bar(5);
> auto bar2 = Bar("bar", 15); // line 31
> }
>
> sctor.d(31): Error: constructor sctor.Bar.this (int a) is not
> callable using argument types (string, int)
>
> Is it by design or is it a bug?
> And, if it is by design, what is the reason for that?
You can use string mixins:
template AddField(T) {
enum AddField = T.stringof ~ ` b;
this(Args...)(` ~ T.stringof ~ ` b, auto ref Args args)
{
this.b = b;
this(args);
}`;
}
struct Bar {
mixin(AddField!string);
int a;
this(int a) { this.a = a; }
}
unittest {
auto bar1 = Bar(5);
auto bar2 = Bar("bar", 15); // line 31
}
More information about the Digitalmars-d-learn
mailing list