property += operator
Dlang User
dlang.user at gmx.com
Thu May 10 19:41:41 UTC 2018
On 5/10/2018 1:43 PM, SrMordred 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 )
I am relatively new to D and I was under the impression that that was a
limitation of @property functions.
But, re-reading the language reference, it gave this example (it returns
something from the write property, which seems odd), I modified to add
refs, and then it seems to work, but I am not sure if it is correct or not:
import std.stdio;
struct Foo
{
@property ref int data() { return m_data; } // read property
@property ref int data(int value) { return m_data = value; } //
write property
private:
int m_data;
}
void main()
{
Foo f;
f.data = 5;
f.data++;
f.data+= 2;
writeln(f.data);
}
More information about the Digitalmars-d-learn
mailing list