www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - typeof(this) at class scope?

reply Bill Baxter <dnewsgroup billbaxter.com> writes:
Is this supposed to work?
----
import std.stdio : writefln;

class Foo {
     alias typeof(this) this_type; // <<--- seems odd but works

     this(int val) { value = val; }

     int value;
}

void main()
{
     auto foo = new Foo.this_type(10);

     writefln(foo.value);
}
-----

It does work currently, but I just want to make sure this is intentional 
and isn't going to go away.  It seems odd that it works because I 
thought 'this' didn't really exist outside method bodies.

The actual use case is in a mixin that is used to implement the bulk of 
of a couple of different variations of the same class.  But the mixin 
needs to know the type of the thing it's implementing for writing 
various methods.  If typeof(this) isn't kosher, then I could pass in the 
type as a template parameter explicitly but that's not as nice.

--bb
Jul 08 2007
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Bill Baxter" <dnewsgroup billbaxter.com> wrote in message 
news:f6rju3$ljo$1 digitalmars.com...
 Is this supposed to work?

 It does work currently, but I just want to make sure this is intentional 
 and isn't going to go away.  It seems odd that it works because I thought 
 'this' didn't really exist outside method bodies.

The page http://www.digitalmars.com/d/declaration.html, in the "typeof" section explains that this is legal.
Jul 08 2007
parent Bill Baxter <dnewsgroup billbaxter.com> writes:
Jarrett Billingsley wrote:
 "Bill Baxter" <dnewsgroup billbaxter.com> wrote in message 
 news:f6rju3$ljo$1 digitalmars.com...
 Is this supposed to work?

 It does work currently, but I just want to make sure this is intentional 
 and isn't going to go away.  It seems odd that it works because I thought 
 'this' didn't really exist outside method bodies.

The page http://www.digitalmars.com/d/declaration.html, in the "typeof" section explains that this is legal.

Great. Thanks for clearing that up for me. --bb
Jul 08 2007