using this instead of typeof(this)
Ivan Kazmenko
gassa at mail.ru
Tue Feb 26 08:28:58 PST 2013
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?
(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.
(3) Is the usage of unnamed parameters and _param_### a language
feature or an implementation-specific detail I should not ever
use?
-----
Ivan Kazmenko.
More information about the Digitalmars-d-learn
mailing list