Question about typeof(this)

Jacob Carlborg doob at me.com
Tue Sep 7 11:33:51 PDT 2010


On 2010-09-07 17:29, Don wrote:
> Jacob Carlborg wrote:
>> I'm reading http://www.digitalmars.com/d/2.0/declaration.html#Typeof
>> where it says:
>>
>> "typeof(this) will generate the type of what this would be in a
>> non-static member function, even if not in a member function. "
>>
>> From that I got the impression that the code below would print the
>> same result, but it doesn't. It prints:
>>
>> main.Bar
>> main.Foo
>>
>> instead of:
>>
>> main.Foo
>> main.Foo
>>
>> Is this a bug or have I misunderstood the docs?
>
> typeof(this) gives the *compile-time* type of this. Inside Bar, it has
> to return 'Bar'.
> typeid(this) gives the *runtime* type of this. So it can work that it's
> Bar is actually a Foo.

I know that typeof(this) is a compile time expression but in this case I 
think the compiler has all the necessary information at compile time. 
Note that I'm not calling "method" on a base class reference, I'm 
calling it on the static type "Foo". In this case I think typeof(this) 
would resolve to the type of the receiver, i.e. the type of"foo".

>
>>
>>
>> module main;
>>
>> import std.stdio;
>>
>> class Bar
>> {
>> void method ()
>> {
>> writeln(typeid(typeof(this)));
>> writeln(typeid(this));
>> }
>> }
>>
>> class Foo : Bar {}
>>
>> void main ()
>> {
>> auto foo = new Foo;
>> foo.method;
>> }
>>


-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list