Template this parameter in constructor

Vlad Leberstein via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 26 05:22:43 PST 2016


On Sunday, 21 February 2016 at 21:48:21 UTC, Steven Schveighoffer 
wrote:
>
> This isn't a bug. Here is what happens.
>
> 1. template this is assigned the compile-time type of the 
> object *when the function is called*.
>
> 2. A base class constructor is called from the next derived 
> constructor. So C2's constructor is called from C3's, and C1's 
> constructor is called from C2's.
>
> So it follows that the template this type will be the next 
> derived constructor (or the type itself if that is the most 
> derived type), because that's the compile-time type the 
> object's ctor is called with.
>

Many thanks to both of you, Steven and Ali! Now this makes much 
more sense!

> I think you may be able to do something like this:
>
> this(T = typeof(this))()
> {
>    super!T();
> }
>
> But I'm not sure if it works.

class C1 {
	this(This = typeof(this))() {
		pragma(msg, "C1 constructor: "~__traits(identifier, This));	
	}
}


class C2 : C1 {
	this(This = typeof(this))() {
		pragma(msg, "C2 constructor: "~__traits(identifier, This));
		super.__ctor!This();
	}
}


class C3 : C2 {
	this(This = typeof(this))() {
		pragma(msg, "C3 constructor: "~__traits(identifier, This));
		super.__ctor!This();
	}
	
}


int main(string[] args) {
	auto test = new C3();
	
	return 0;
}

Compilation output:
C3 constructor: C3
C2 constructor: C3
C1 constructor: C3
C1 constructor: C1
C2 constructor: C2
C1 constructor: C2

A little bit modified solution compiles but doesn't work as 
expected(tested on dmd 2.070) and produces some quite strange 
results and I really don't get why. But now it's not critical for 
me cause I managed to solve my initial problem with major 
refactoring.

Many thanks again!


More information about the Digitalmars-d-learn mailing list