Struct inheritance

Derek Fawcus dfawcus+dlang at employees.org
Tue Dec 3 19:15:39 UTC 2024


On Thursday, 19 September 2024 at 15:56:06 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
> As an idea this has come up in Razvan's DConf 2024 talk.
>
> 1. Support inheritance on struct, for other structs.
>
> ```d
> struct Parent {
>     ...
> }
>
> struct Child : Parent {
>     ...
> }
> ```
>
> 2. ``opDispatch`` function, may work in place of ``alias this`` 
> when no parent exists.
>
> ```d
> struct Parent {
>     T thing;
>     ref T opDispatch(string:"")() {
>         return this.thing;
>     }
> }
>
> struct Child : Parent {
> }
>
> Child child;
> T got = child;
> ```

As I recall, the main purpose of 'alias this' is to offer 
implicit conversion of types.  There is also the ability to have 
a member function called (property-like?), which seems like a 
somewhat different purpose.

When I first saw this inheritance suggestion mentioned (possibly 
in a recording of one of the DConf sessions), it struck me that 
something like the 'struct embedding' together with its implicit 
conversion for member functions on the embedded type may provide 
a similar mechanism.

This is something which is offered by Go/Limbo/Alef/Ken-C, the 
latter being used as the Plan 9 C compiler.

As I recall in the latter it was used for something like:

```C
struct Lock {
   ...
};

bool lockit(struct Lock *);

struct Foo {
    ...
    Lock;
    ...
};

void something(/* ... */)
{
     struct Foo *foo = something_returning_Foo(/* ... */);

     if (!lockit(foo) {
         /* some error handling */
     }

     ...
}
```

Where the use of lockit() above is then called with '&foo->Lock' 
as an implicit conversion.

Personally, I'd rather have a struct like (POD) thing, even with 
member functions, which does not allow for the possibility of 
classful behaviour.  If classful behaviour is desired, then 
somehow adjust classes so that they can be easily used as 
non-reference types.





More information about the dip.ideas mailing list