How to get child class Type and members from parent class?
mipri
mipri at minimaltype.com
Wed Nov 20 10:28:45 UTC 2019
On Wednesday, 20 November 2019 at 10:05:11 UTC, zoujiaqing wrote:
> import std.stdio;
>
>
> class A
> {
> this(T)(T t)
> {
>
> }
>
> void write()
> {
> T _this = cast(T) this;
> writeln(this.v);
Here, class A knows that a 'v' member is present. So why not just
put that member in class A, and let B inherit it? If this method
won't apply to some other child classes, you can have an
intermediate class that adds the v member and specializes this
method to use it, and all the v children can inherit from A
through
that intermediary.
I think what you're wanting to do is a reversal of OO design.
Maybe you can use proper OO instead, or maybe you'd prefer a
discriminated union if different children will have different
types
for v. Like in an FP lang: https://github.com/pbackus/sumtype
> }
> }
>
> class B : A
> {
> string v = "hello";
> }
>
> void main()
> {
> auto b = new B;
>
> writeln(b.write()); // print hello
> }
More information about the Digitalmars-d-learn
mailing list