Inner Classes vs. Inner Structs

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Mar 11 15:33:45 UTC 2018


On Sunday, March 11, 2018 13:19:39 Mike Franklin via Digitalmars-d-learn 
wrote:
> This works:
>
> ```
> class S {
>      int n, m;
>      int sum() { return n + m; }
>      Inner!(sum) a;
>
>      class Inner(alias f){
>          auto get() {
>              return f();
>          }
>      }
> }
> ```
>
> This doesn't:
>
> ```
> struct S {
>      int n, m;
>      int sum() { return n + m; }
>      Inner!(sum) a;
>
>      struct Inner(alias f){
>          auto get() {
>              return f(); // Error: this for sum needs to be type S
> not type Inner!(sum)
>          }
>      }
> }
> ```
>
> The only difference between the two is one one uses classes, the
> other uses structs.  My question is, under the current semantics
> of D, shouldn't the two work the same?  That is, shouldn't the
> inner struct in the second example have an implicit context
> reference to the outer struct?  Is this a bug?

No, it's on purpose, and the only reason that non-static, nested classes
have access to the class they're declared in is for compatibility with Java,
which doesn't have structs. Also, I suspect that if D were being designed
now, it would treat nested classes the same as nested structs rather than
treating nested structs like it currently does nested classes. Some of D's
design has a number of Java-isms because of when D was first started and the
fact that it didn't have some of features that it has now. Certainly, if we
included the feature at this point if we were redesigning the language, I
expect that it would only be to make porting Java code easier.

Regardless, changing the current behavior would break code, so I doubt that
it's going to change. IIRC, DWT relies on the behavior with classes (since
it's code ported from Java), and while I question that all that much D code
outside of DWT takes advantage of non-static, nested classes, I suspect that
having non-static, nested structs suddenly act differently from static,
nested structs would break a fair bit of D code. There is of course no way
to know how much code would break with either change, but I doubt that
Walter would agree to the potential code breakage in either direction.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list