Improvement to struct inheritance possible?
Steven Schveighoffer
schveiguy at gmail.com
Thu Jan 18 15:18:51 UTC 2024
On Thursday, 18 January 2024 at 07:10:49 UTC, Danilo wrote:
> The following code does not work, and I think it may be a bug
> or could need an enhancement:
>
> ```d
> module app;
> import std;
>
> void main() {
> auto x = new Derived(10, 20);
> }
>
> struct Base {
> int a;
> }
>
> struct Derived
> {
> Base base;
> int b;
> alias this = base;
>
> @disable this();
>
> // `a` is not available for use with constructor parameters.
> //
> this( typeof(a) _a, typeof(b) _b ) {
> //
> // inside the body of the constructor, `a` is available!
> //
> a = _a;
> b = _b;
>
> writeln( a, ", ", b );
> }
> }
> ```
>
> The use of `typeof(a)` as a constructor parameter gives:
> Error: undefined identifier `a`
>
> Instead I have to explicitely use:
> ```d
> this( typeof(this.a) _a, typeof(b) _b )
> // or
> this( typeof(base.a) _a, typeof(b) _b )
> ```
Just FYI, it's kind of a special case that `typeof(this)` works
in this context -- there is no "this" at declaration level, it
only exists as a parameter to a function. D allows using
typeof(this) to mean "the type of an instance" during
declarations because it would be awful otherwise.
So I think you are playing around the edge of this "special case"
and that's why it's not working.
I'm actually surprised `typeof(this.a)` works.
-Steve
More information about the Digitalmars-d
mailing list