Hi,
I'm experimenting with the behaviour of properties in D, as I am
writing some classes that are being used in a mixture of const
and non-const functions.
I've found a couple of things that I'd just like to check. First
perhaps I should say what I would expect from working with
properties in a mixed const / non-const environment.
* I expect getting a property to work for both const and
non-const.
* I expect setting a property to only work for non-const.
I found that to get this behaviour I needed to declare any getter
return type as well as the property function as "inout". This
seemed to work for getter / setter function pairs as well as the
"@property auto ref" idiom.
I also noticed something that was unexpected to me as a beginner,
that the getter / setter pairs are not valid with the "+="
operator but the "auto ref" is. I guess this is down to the way D
interprets the syntax during compilation and the differences
between how the 2 different implementations access the data. But
it is none the less surprising that the flowing are not
syntactically equivalent.
t.val = t.val + 1;
t.val += t.val;
Anyway here is my test code:
module test;
class Test {
private:
int _val;
public:
@property inout(int) val() inout {
return _val;
}
@property void val(int val) {
_val = val;
}
@property auto ref inout(int) val2() inout {
return _val;
}
}
void test(Test t) {
import std.stdio : writeln;
writeln("--- test ----");
writeln("val: ", t.val);
writeln("val2: ", t.val2);
}
void test2(in Test t) {
import std.stdio : writeln;
writeln("--- test 2 ----");
writeln("val: ", t.val);
writeln("val2: ", t.val2);
}
void main() {
auto t = new Test;
//t.val += 100; // BAD - not an lvalue
t.val = t.val + 100;
test(t);
t.val2 += 100; // OK
test2(t);
}