www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - typeof(this) and subclasses

reply Serg Kovrov <kovrov no.spam> writes:
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.
Aug 12 2006
next sibling parent Serg Kovrov <kovrov no.spam> writes:
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.
Aug 12 2006
prev sibling parent kris <foo bar.com> writes:
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?
Aug 12 2006