alias this doesn't work for properties.
Adam D. Ruppe
destructionator at gmail.com
Thu Aug 1 19:46:59 PDT 2013
On Friday, 2 August 2013 at 00:36:19 UTC, JS wrote:
> Realize that the ultimate goal is to assign 3 to x?
A working solution is to just use opAssign. I think of alias this
as being implicit cast to , whereas opAssign is implicit cast
from (well, sort of, it only works on assignments, but there's
also constructors you can do. Where it falls short of full
implicit cast is stuff like function calls)
Anyway, try this:
class A
{
double x;
@property double X() { return x; }
@property double X(double v) { return x = v; }
alias X this;
// new
A opAssign(double rhs) { x = rhs; return this; }
}
Now:
A a = new A();
a = 3.14; // ok
Then the next question is b.Y = 3, which is one of those cases
where it just isn't going to work like that. Y is pretty explicit
about *wanting* an A, this isn't setting to an A, this would
actually be implicit construction which is generally a no-no in D.
However, if you add:
@property A Y(double v) { return a = v; }
to class B, then it will compile, with a = v calling A.opAssign.
A cool thing about opAssign that aias this doesn't do right now
is it can be templated or you can overload it, and handle a vast
variety of types.
More information about the Digitalmars-d
mailing list