Struct inheritance
Derek Fawcus
dfawcus+dlang at employees.org
Tue Dec 3 20:19:20 UTC 2024
On Tuesday, 3 December 2024 at 19:25:08 UTC, Richard (Rikki)
Andrew Cattermole wrote:
> On 04/12/2024 8:15 AM, Derek Fawcus wrote:
>> 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.
>
> It is two functionalities yes.
>
> Which is why I've included both the inheritance as well as the
> reparenting behavior. Otherwise it isn't a complete replacement.
> As a syntax that would imply multiple of these are possible.
Yes, but it is literally equivalent to explicitly embedded one
struct in another, which is already possible. So one could have:
```C
struct Foo;
struct Bar;
struct Wrapper {
...
Foo;
Bar;
...
};
```
Which is just sugar for this:
```C
struct Wrapper {
...
struct Foo Foo;
struct Bar Bar;
...
};
```
It is just that having the embedded form allows the implicit
conversion to happen, as it is a simple unambiguous sugar for
accessing the appropriate member.
> Classes in D do not support multiple parent classes, so I don't
> think adding it for structs is appropriate.
Except D also already allows the explicit form above, but not the
sugar for the field reference. This is not inheritance, so there
are no issues with embedding multiple structs, no diamond pattern
issues, etc. (I believe the Go spec explains all of this.)
What this gives is the implicit field conversion which 'alias
this' seems to offer some form of, but in a different syntactical
form, and allowing multiple such conversions.
However it probably won't cover all implicit conversion uses,
e.g. 'alias this' to an 'int' member, then assigning the struct
to an int var. The scheme I'm suggesting only really covers
calling functions with argument conversion.
> If you don't need multiple parents, then the existing syntax
> works fine.
>
> ```d
> struct Parent {
> }
>
> struct Foo : Parent {
> }
> ```
Would your proposal allow:
```d
struct Grandad {
}
struct Dad : Grandad {
}
struct Child : Dad {
}
```
(I'm not sure if the scheme I mention does, I'd have to reread
the specs; but I believe it doesn't).
More information about the dip.ideas
mailing list