February 23, 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

February 23, 2011
On Wed, 23 Feb 2011 10:34:04 -0500, spir <denis.spir@gmail.com> wrote:

> 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?

It allows *some* simulation of inheritance.  However, it does not implement polymorphism.

What it does is allow specialization and upcasts.  For example:

struct S
{
   int x;
   void foo() {}
}

struct T
{
   S s;
   void foo2() {};
   int y;
   alias s this;
}

T t;
t.foo(); // translates to t.s.foo();
t.x = 5; // translates to t.s.x = 5;
S s = t; // translates to S s = t.s;

-Steve