Struct inheritance
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Thu Dec 5 23:10:46 UTC 2024
On 06/12/2024 11:41 AM, Jonathan M Davis wrote:
> On Thursday, September 19, 2024 9:56:06 AM MST Richard Andrew Cattermole
> (Rikki) via dip.ideas 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;
>> ```
>
> After that talk, I discussed struct inheritance briefly with Walter, and his
> idea was that if we did it, there would be _no_ conversions of any kind that
> came from it. It would purely be a way to have a struct inherit all of the
> fields and member functions from the "parent" struct and as such would
> essentially be the compiler copying and pasting that code into the struct
> doing the inheriting.
>
> So, it would provide a way to inherit / copy the implementation, but the
> types would be completely divorced from one another in terms of how they
> were used.
>
> Personally, I think that that's the right approach, since it's the issues
> around implicit conversions that are the core problem with alias this, and
> it avoids all issues with regards to slicing objects (which is the primary
> reason why classes in D are on the heap instead of on the stack like they
> can be in C++).
>
> - Jonathan M Davis
From my perspective that is mostly an implementation detail.
The reason it is not fully an implementation detail is due to methods
effectively having what I've been calling ``@reinterpretAsChild`` turned on.
We can still make overrides, and is expression to check if it inherits
from the parent type to work.
I'm ok with this approach. It simplifies a bunch of problems down.
More information about the dip.ideas
mailing list