How to alias

Adam D Ruppe destructionator at gmail.com
Fri Jan 14 17:56:48 UTC 2022


On Friday, 14 January 2022 at 17:48:41 UTC, kyle wrote:
> I'm trying to use ```alias``` in an operator overload to reduce 
> typing, but what gets aliased is not what I expect.

alias works in term of compile-time names, not values. This means 
the `this` value, being run time, gets discarded.

alias b = rhs.num;

drops the this, instead doing something more like `alias b = 
Broke.num;`. It'd work if it was static, or if you re-attach the 
this later, which is what actually happens in that assert, but 
not otherwise. This commonly surprises people but the behavior is 
sometimes useful, i just wish it didn't look the same as 
something so different.

Easiest thing to do instead is to just use a ref helper function:

             ref b() { return rhs.num; }
             assert(&b() != &this.num); //this works now

(With the -preview=shortenedMethods you can write it `ref b() => 
rhs.num;` too nut in both cases, you must call the function as 
b() when you use it)


Or, of course here, the num is just a value so you can simply use 
an intermediate variable too.



More information about the Digitalmars-d-learn mailing list