Thread overview | |||||
---|---|---|---|---|---|
|
August 12, 2006 typeof(this) and subclasses | ||||
---|---|---|---|---|
| ||||
Hello D-people =) Is there a way to get type of subclass in method defined in superclass, but called in subclass? Here a class hierarchy: > class Foo > { > static typeof(this) create() > { > // ... some init code > return new typeof(this)(init); > } > } > > class FooBar : Foo > { > /* FooBar doesn't overriding create() */ > } and I'd like to create them as follows: > auto f = Foo.create(); // f is instance of Foo > auto b = FooBar.create(); // b should be instance of FooBar But, because of 'typeof(this)' appears to be evaluated where it defined instead of where it called (sorry for possible misuse of terminology, but I hope you got my idea), 'b' is type of 'Foo' instead of desired 'FooBar'. -- serg. |
August 12, 2006 Re: typeof(this) and subclasses | ||||
---|---|---|---|---|
| ||||
Posted in reply to Serg Kovrov | Forgot to mention, currently as workaround I use templates:
T Create(T)()
{
// ... some init code
return new T(init_result);
}
auto f = Create!(Foo)(); // f is instance of Foo
auto b = Create!(FooBar)(); // b is instance of FooBar
But `FooBar.create()` me like much better =)
--
serg.
|
August 12, 2006 Re: typeof(this) and subclasses | ||||
---|---|---|---|---|
| ||||
Posted in reply to Serg Kovrov | Serg Kovrov wrote:
> Hello D-people =)
>
> Is there a way to get type of subclass in method defined in superclass, but called in subclass?
>
> Here a class hierarchy:
>
>> class Foo
>> {
>> static typeof(this) create()
>> {
>> // ... some init code
>> return new typeof(this)(init);
>> }
>> }
>>
>> class FooBar : Foo
>> {
>> /* FooBar doesn't overriding create() */
>> }
>
>
> and I'd like to create them as follows:
>
>> auto f = Foo.create(); // f is instance of Foo
>> auto b = FooBar.create(); // b should be instance of FooBar
>
>
> But, because of 'typeof(this)' appears to be evaluated where it defined instead of where it called (sorry for possible misuse of terminology, but I hope you got my idea), 'b' is type of 'Foo' instead of desired 'FooBar'.
>
I suspect the "typeof(this)" is evaluated statically, at compile time. You might as well write "Foo" instead?
|
Copyright © 1999-2021 by the D Language Foundation