How can I make typeof(this) return the type of a calling derrived class from a function in a base class?
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 16 07:23:49 PDT 2017
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.
More information about the Digitalmars-d-learn
mailing list