How can I make typeof(this) return the type of a calling derrived class from a function in a base class?
Milan Suk via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 16 07:17:59 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)); }
> ...
> }
>
> 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"
}
More information about the Digitalmars-d-learn
mailing list