Question about typeof(this)

Stanislav Blinov stanislav.blinov at gmail.com
Tue Sep 7 12:50:54 PDT 2010


Jacob Carlborg wrote:
> On 2010-09-07 17:34, Stanislav Blinov wrote:
>> 07.09.2010 17:00, Jacob Carlborg пишет:
>>> 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?
>>>
>>>
>>> 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;
>>> }
>>>
>> I don't think it's a bug. More of it, Expressions page in the docs has
>> your very same example in Typeid section.
>>
>> Inside Bar.method, typeof(this) yields a type (Bar), and typeid for
>> types gets you, well, typeid for types :) typeid(this), hovewer, should
>> get typeinfo for most derived class, which it does.
> 
> No it's not the same example. In the example on the Expressions page 
> typeid is used on the static type A with the dynamic type B. I have both 
> the static and dynamic type Foo. I think in my example the compiler have 
> all the necessary information at compile time and typeof(this) would 
> resolve to the type of the receiver, i.e. the type of "foo" which is Foo.
> 
I still don't see the difference. But even if there is one... It may be 
that in this particular case compiler may have sufficient information, 
but there are plenty of cases when it may not: e.g. class Foo is in a 
separate module or even separate library. After all, method actually has 
signature Bar.method(), not Foo.method().


More information about the Digitalmars-d-learn mailing list