Fixing D's Properties

Christopher Wright dhasenan at gmail.com
Sun Aug 19 11:24:27 PDT 2007


Ender KaShae wrote:
> Chad J Wrote:
> 
> 
>> If the proposed solution is not good enough, please give a better one. 
>> Suggestions are welcome and encouraged.
>>
> 
> I suggest something similar to python properties, for those who are not familior with it a property is created with property(getter, setter) so with my idea property (or inout or some other keyword) would be a new type, sort of like a function or delegate, but with behavior like that described by Chad.  The syntax would be somthing like:
> 
> int getX(){ return x;}
> void setX(int i){x = i;}
> 
> property int X(&getX, &setX);

Or:

property int X({ return x; }, (int i) { x = i; });

> the problem is that unlike in python we cannot use keywords to set paramaters so some syntax would have to be made for write only properties, maybe if we used inout instead of property:
> 
> //read only
> in int x(&getX);
> //write only
> out int x(&setX);
> //read and write
> inout int x(&getX, &setX)

Or:
property int ReadonlyX({ return x; }, null);
property int WriteonlyX(null, (int i) { x = i; });

> any read would call the reading function (.reader of the property object)
> any write would call the writing function (.writer of the property object)

This is good -- getting the address of the getter and setter functions 
(&obj.X.reader) will be useful. And getting the address of the property 
will still allow you to get and set the property.

Templates might have trouble with it, though.

> so obj.x++
> 
> would be the same as:
> obj.x.writer(obj.x.reader() + 1)
> 
> when read the property will actually return a special wrapper that sends itself to the writer whenever it is assigned to 
> the address of the property cannot be used as a function or delegate, but can be used as the address of the type 

The address of the property should be an address to a property struct, 
whose getters and setters would work as usual.

Hm...

---
class Property(T) {
    T* value;
    public void opIncrement() { *value++; }
    public void opDecrement() { *value--; }
    public T opAdd(U) (U addend) { return *value + addend; }
    // ...
}

class MyClass {
private:
    int _x;
public:
    Property!(int) X;
    this() {
       // slightly ugly...
       X = new Property!(int)(&_x);
    }
}
---

If you could overload the dot operator as well, then this and some 
template magic with __traits would give you everything you want.

Without the dot operator, you get everything you need anyway for basic 
types. And classes are already taken care of. Structs are left out, though.



More information about the Digitalmars-d mailing list