alias this for inheritance

spir denis.spir at gmail.com
Wed Feb 23 07:34:04 PST 2011


Hello,

I have read several times that alias this is a way to implement inheritance for 
structs.
I am simply unable to imagine how to use this feature that way. Has anyone an 
example?

As I understand it, alias this constructs a proxy that delegates some or all of 
of its behaviour to its 'alias' member. Full stop. How, from this, can one 
construct for instance such a minimalistic subtyping hierarchy --and make it 
work as expected:

struct S {
     bool b;
}
struct SI {
     bool b;
     int i;
     void write () { writeln("int: ", this.i); }
}
struct SF {
     bool b;
     float f;
     void write () { writeln("float: ", this.f); }
}

unittest {
     auto si = SI(true, 1);
     si.write();
     auto sf = SF(false, 1.1);
     sf.write();
     // challenge:
     S[2] a;
     a[0] = si; a[1] = sf;
     foreach (s ; a) s.write();
}

The equivalent using class subtyping would be trivial (indeed):

class C {
     bool b;
     void write() {};
}
class CI : C {
     int i;
     this (int i) { this.i = i; }
     override void write () { writeln("int: ", this.i); }
}
class CF : C {
     float f;
     this (float f) { this.f = f; }
     override void write () { writeln("float: ", this.f); }
}

unittest {
     auto ci = new CI(1);
     ci.write();
     auto cf = new CF(1.1);
     cf.write();
     // works:
     C[2] a; a[0] = ci; a[1] = cf;
     foreach (c ; a) c.write();
}

Help welcome, thank you,
Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list