struct inheritance

Reiner Pope some at address.com
Thu Aug 30 23:14:35 PDT 2007


Bill Baxter wrote:
> kris wrote:
>> Perhaps a bigger problem is this:
>>
>> #       struct M { int a; }
>> #       struct S {
>> #          int b;
>> #          import M;
>> #       }
>>
>> Now, S is no longer derived from M. 
> 
> Well for the 'import' syntax it wouldn't be so bad.  The compiler could 
> just say "imported members will always appear first".  With the alias 
> syntax that would be a bit weirder since there's already an "M m" right 
> there in the struct (which I assume you would still be able to access 
> via the .m).  Since there's a visible member there, it makes less sense 
> for the compiler to move the fields around.
> 
> 

I'm not sure why imported members do have to appear first. Is there a 
reason that S is derived from M only if M is the first member of S? In 
lieu of a vtbl, S being derived from M presumably only means that S can 
be implicitly converted to M. So what's wrong with writing

struct M { int a; }
struct S {
     int b;
     M m;
     alias m this;

     M opImplicitCastTo() { return m; }
}

>> Hence, it would seem the right way to do this is to take it out of the 
>> hands of the developer and do something akin to
>>
>> #    struct S : M
>>
>> as had been suggested previously. Sure, that particular syntax may 
>> mean something else to some C++ folks, but at least the intent is 
>> clear and the /outcome/ is consistent.
> 
> Yeh.  I agree.  I think that syntax would be better too.  I was just 
> assuming that *not* using that syntax was something that we wouldn't 
> change Walter's mind about.  But maybe there's hope.

I think that "alias this" may become more interesting when aliases work 
with any expression. You could write things like

struct S {
     M m;
     alias m.a this;
}

You can't really express this neatly with inheritance (in my opinion). 
Of course, the import syntax works just as well, but I think alias 
expresses exactly what you're doing, and doesn't require introduction of 
a distinct concept to the language.

    -- Reiner



More information about the Digitalmars-d mailing list