struct subtyping?

spir denis.spir at
Sun Oct 24 16:11:14 PDT 2010

On Sun, 24 Oct 2010 23:41:07 +0200
"Simen kjaeraas" <simen.kjaras at> wrote:

> spir <denis.spir at> wrote:
> > I would like to learn about possible workarounds, or other alternative  
> > approaches to such problems, if ever you now any.
> Basically, you probably want to use alias this:
> It lets you subtype structs by propagating member field/function access
> to a member, if the struct or class does not implement the field or
> function itself.

All right, if I understand correctly, this is very similar to Lua metatables. (The __index field of an object's metatable tells what to do when slot lookup fails.) If I'm right, this would allow type extension by storing additional fields/methods on a kind of sub-struct? (But not method overriding, I guess; which anyway would require type-bound method dispatch).
I also considered having a void* field where type-specific slots would be stored. Or unions (but I don't know how they work actually). Alias this seems better since lookup mechanism would be "automagic", if I understand correctly.

> alias this is panacea - if a function expects a base struct, and returns
> it after doing some alterations, you cannot cast the result to a subtype
> (see below).

Do you mean "alias this _not_ is panacea"?

> > Also, I would love to read about the rationale for _not_ having struct  
> > type hierarchies (probably this would not be a big deal, since D has it  
> > for classes (*)) Or maybe I have simply not correctly understood  
> > available docs?
> The main reason is the slicing problem. If the language lets a user store
> a struct that is a subtype of another struct, and that adds fields, in a
> location where space is only allocated for the base struct, the extra
> fields are eaten by grues, and bugs appear.

All right, thank you! (This is also the reason why Oberon prohibits returning from funcs dynamic arrays and record: their size is not known at compile-time -- the latter because they can be extended/subtyped. So that we need to use pointers).

-- -- -- -- -- -- --
vit esse estrany ☣

More information about the Digitalmars-d-learn mailing list