Template mixins and struct constructors

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 2 04:54:51 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?

I would say it is by design. What this will generate is something 
like:

struct Bar {
     static struct _scope {
         string b;
         this(Args...)(string b, auto ref Args args) {
             this.b = b; this(args);
         }
     }
     int a;
     this(int a) { this.a = a; }
}




More information about the Digitalmars-d-learn mailing list