alias fails to compile

Alex AJ at gmail.com
Mon Apr 22 14:07:11 UTC 2019


On Monday, 22 April 2019 at 08:02:06 UTC, Arun Chandrasekaran 
wrote:
> What am I doing wrong here?
>
> struct A
> {
>     union B
>     {
>         int bb;
>     }
>     B b;
>     alias aa = b.bb;
> }
>
> void main()
> {
>     A a = A();
>     // a.b.bb = 4; // works
>     a.aa = 4; // fails
> }
>
>
> https://run.dlang.io/is/kXaVy2

aa is a "static" semantic.

your statement a.aa does not get translated in to a.b.bb like you 
think it does.

You are doing nothing any different than A.aa = 4.

which, when you realize this you'll understand the "need this" 
error.


It's as if you are doing

> struct A
> {
>     union B
>     {
>         int bb;
>     }
>     B b;
> }
      alias aa = A.b.bb;

aa = 4;

which is like trying to say

A.b.bb = 4;


In D we can access "static" stuff using the object and so this 
can make things look like the mean something they are not.

If you could magically pass the this to it using something like 
UFCS then it could work.

import std.stdio;
struct A
{
     union B
     {
         int bb;
     }
     B b;
     alias aa = (ref typeof(this) a) { return &a.b; };
}

void main()
{
     A a = A();
     a.b.bb = 4;
     a.aa(a).bb = 5;
     writeln(a.aa(a).bb);
}

But here a.aa is not aa(a) and UFCS does not work so one must 
first access the alias and then pass the this.

Basically you are not going to get it to work. Just not how the 
semantics works.

It would be nice if a.aa(a) could reduce to a.aa as is UFCS was 
smart enough to realize it could pass it to the alias as this, 
but it doesn't.

else one might could do

alias aa = this.b.bb;

and

a.aa = 4;






More information about the Digitalmars-d-learn mailing list