using this instead of typeof(this)

Kenji Hara k.hara.pg at gmail.com
Tue Feb 26 10:22:02 PST 2013


On Tuesday, 26 February 2013 at 16:28:59 UTC, Ivan Kazmenko wrote:
> Hi!
>
> I have recently experimented with ways to express the exact 
> instantiated type of a generic struct, and found that I can in 
> some cases use "this" as that type.
>
> Here is a sample program (DMD 2.062) demonstrating various uses 
> of "this" as a type:
>
> -----
> import std.stdio;
>
> struct S
> {
> 	int x = 1;
> 	int y = 0;
>
> 	void f ()
> 	{
> 		y = 1;
> 	}
>
> 	this (this) // postblit constructor
> 	{
> 		x = 10;
> 	}
>
> 	this (ref this) // not a postblit constructor
> 	{
> 		x = 100;
> 	}
>
> 	this (ref this, this f, typeof (this), this, ref this g)
> 	{
> 		x = 1000 + _param_0.x + f.x + _param_2.x + _param_3.x + g.x;
> 	}
> }
>
> void main ()
> {
> 	S a;
> 	a.f ();
> 	S b = a;
> 	S c = S (a);
> 	S d = S (a, a, a, a, a);
> 	writefln ("%s %s", a.x, a.y); // 1 1
> 	writefln ("%s %s", b.x, b.y); // 10 1 (copied b.y = a.y)
> 	writefln ("%s %s", c.x, c.y); // 100 0 (did not copy)
> 	writefln ("%s %s", d.x, d.y); // 1032 0 (refs add 1, non-refs 
> add 10)
> }
> -----
>
> And so I wonder:
>
> (1) Should I refrain from using this as a type, is it a bug?

It is definitely a bug. I cannot believe that such horrible bug 
is still there.
If you have a time, could you please file it in bugzilla?

http://d.puremagic.com/issues/

> (2) A matter of style: what is the idiomatic way to take the 
> exact type of a templated struct? For example, which method 
> signature to return a typeof(this) value is "better" in which 
> way if all have the same effect:
> -----
> struct S (A, B, C)
> {
> ...
> 	auto method () {...}
> 	S method () {...}
> 	S !(theA, theB, theC) method () {...}
> 	typeof (this) method () {...}
> }
> -----
> Note that S, theA, theB and theC can get lengthy.

Returning S, S!(...), and typeof(this) are identical. You can use 
them as you favorite.
auto return is a little different with others. To infer return 
type, the method body is aggressively analyzed in compilation. If 
the method has mutual call with another auto return function, it 
will cause 'forward reference error'.

> (3) Is the usage of unnamed parameters and _param_### a 
> language feature or an implementation-specific detail I should 
> not ever use?

It is implementation specific. You must not rely on that.

Kenji Hara


More information about the Digitalmars-d-learn mailing list