| Thread overview | ||||||
|---|---|---|---|---|---|---|
|
June 16, 2017 How can I make typeof(this) return the type of a calling derrived class from a function in a base class? | ||||
|---|---|---|---|---|
| ||||
If I have something like the following:
class A {
void foo(){ writeln(typeof(this)); }
...
}
class B : A {
...
}
And I want the results:
A a = new A;
B b = new B;
a.foo(); // prints "A"
b.foo(); // prints "B"
How would I go about doing that? At the moment b.foo() is printing "A".
| ||||
June 16, 2017 Re: How can I make typeof(this) return the type of a calling derrived class from a function in a base class? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Lester | On Friday, 16 June 2017 at 13:46:14 UTC, Lester wrote: > If I have something like the following: > > class A { > void foo(){ writeln(typeof(this)); } > ... > } > > class B : A { > ... > } > > And I want the results: > > A a = new A; > B b = new B; > a.foo(); // prints "A" > b.foo(); // prints "B" > > How would I go about doing that? At the moment b.foo() is printing "A". What about something like this? class A {} class B : A {} void foo(T)(T object) { import std.stdio : writeln; writeln(object.classinfo.toString); // you can use whatever property you want... } void main() { A a = new A; B b = new B; a.foo(); // prints "test.A" b.foo(); // prints "test.B" } | |||
June 16, 2017 Re: How can I make typeof(this) return the type of a calling derrived class from a function in a base class? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Lester | On Friday, 16 June 2017 at 13:46:14 UTC, Lester wrote: > If I have something like the following: > > class A { > void foo(){ writeln(typeof(this)); } try one of these: http://dlang.org/spec/template.html#TemplateThisParameter Though note that the this in there is still the static type at the usage point. So: B b = new B; b.foo; // B, because it is called through a B but A b = new B; b.foo; // A, because it is called through the A interface You can also do runtime stuff with typeid/classinfo (they return the same thing) or simply override the function in the child class (often preferred). Depends on exactly what you need it for. | |||
June 16, 2017 Re: How can I make typeof(this) return the type of a calling derrived class from a function in a base class? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | Thanks for the responses guys :) I ended up using a foo(this T) and it works! Thanks again for your help. | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply