Virtual functions and inheritance
Daniel Kozák via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jan 27 00:19:31 PST 2015
V Tue, 27 Jan 2015 04:38:57 +0000
David Monagle via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> napsáno:
> Hi guys,
>
> I'm a former C++ developer and really enjoying working with D
> now. I have a question that I hope some of you may be able to
> answer.
>
> class Parent {
> @property string typeName() {
> return typeof(this).stringof;
> }
> }
>
> class Child : Parent {
> }
>
> void main() {
> auto p = new Parent;
> auto c = new Child;
> assert(p.typeName == "Parent");
> assert(p.typeName == "Child");
> }
>
>
> I'm looking for an explanation as to why this doesn't work, then
> a suggestion for how I may achieve child classes being able to
> generate a string description of their own type, without
> redefining the typeName property on each child. (I'm currently
> solving this with a mixin, but I was hoping for a better solution.
>
> I'm assuming it doesn't work because either typeof(this) or
> .stringof is evaluated at compile time?
You can use this T:
class Parent {
@property string typeName(this T)() {
return T.stringof;
}
}
class Child : Parent {
}
void main() {
auto p = new Parent;
auto c = new Child;
assert(p.typeName == "Parent");
assert(c.typeName == "Child");
}
More information about the Digitalmars-d-learn
mailing list