read-only access

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 2 12:47:21 PDT 2010


On Tuesday 02 November 2010 12:33:41 spir wrote:
> Hello,
> 
> Is the D way to make read-only symbols (of a class, struct, module) to
> write a getter for a private symbols?
> 
> Additional question: just realised one can omit () on func calls! Is this
> systematic when a func has no param? I thought it was not the case,
> because it does not work with writeln (the first func on which I tried,
> indeed!). Is it only because writeln is parameterized (with (T...)) or is
> there any other reason I'm not aware of?
> 
> struct P {
>     private int my_i;
>     int i() {return this.my_i;}
>     void doit() {writeln("...doing...");}
> }
> void main () {
>     auto p = P(1);
>     writeln("p.i: ",p.i);
>     p.doit;
> }
> 
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

Historically, you could call any function which returned a value and took no 
parameters without parens, and you could call any function that was void and 
took a single parameter by assigning to it. e.g.

int getter() { return value;}
void setter((int value} {this. value = value;}

auto x = obj.getter;
obj.setter = x;

This included non-member functions, which meant that you could do things like 
writeln = 7; instead of writeln(7); Something was done a while back to make it 
so that writeln() didn't work that way. I don't know what. Eventually, however, 
the idea is that only functions marked with @property will work that way. e.g.

@property int getter() { return value;}
@property void setter((int value} {this. value = value;}

If they don't have the property attribute, then they won't work without parens 
(and in fact, you won't be able to use parens with them). That is how it's 
outlined in TPDL (The D Programming Language by Andrei Alexandrescu). However, 
dmd has not reached that point. It will still allow property functions to be 
used with parens and non-property functions to be used as property functions as 
long as they're void and take one parameter or return a value and take no 
parameters. So, once dmd is up-to-date with regards to TDPL, you'll no longer be 
able to use arbitrary functions as properties, but for the moment, you can.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list