property += operator

Jonathan M Davis newsgroup.d at
Thu May 10 21:16:12 UTC 2018

On Thursday, May 10, 2018 18:43:40 SrMordred via Digitalmars-d-learn wrote:
> struct T
> {
>      int x;
>      @property ref X(){ return x; }
>      @property X(int v)
>      {
>          x = v;
>      }
> }
> T t;
> t.X += 10;
> The setter 'x = v' are not executed because i´m returning the
> reference of x.
> And without the 'ref' the compiler complains because 'x' is not a
> lvalue.
> Any solution to make it work like native arr.length+=10 works?
> ( I Thought on returning a struct with "+=" operator but it is a
> strange solution )

Just in general, I would suggest that you not provide both a getter and a
setter if the getter returns by ref. If that's what you're doing, then just
use the getter as the setter. In general though, with getters and setters,
you can only get and set a value. Stuff like += won't work unless you return
by ref (which frequently makes having a function instead of just making the
variable public kind of pointless) or if you play games like returning an
object that overrides opOpAssign!"+" which gets kind of weird and
complicated, albeit sometimes reasonable and useful.

IIRC, there's a DIP for trying to make += work with just getters and
setters, but I don't know if we're ever going to see anything like it in the

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list