Properties

Michiel Helvensteijn nomail at please.com
Thu Jan 8 03:43:56 PST 2009


dsimcha wrote:

> Yeah, this has been mentioned in the past before.  The most obvious way to
> make it work w/o any breaking or significantly bulk-adding changes would
> be to define foo.length += 8 to mean foo = foo.length() + 8, or
> foo.length++ mean foo =
> foo.length + 1.  This would be pure syntactic sugar, as it is when working
> with primitives.
> 
> One problem that comes to mind is if, instead of length, which is
> presumably some kind of integer, you have a property for some user defined
> type with operator
> overloading.  This user-defined type could define opAdd to do something
> arbitrarily different from opAddAssign.  Even if we assume that no
> reasonable programmer would do this and treat this as a "who cares?"
> corner case, there's still the problem of opInc and opAddAssign being much
> cheaper in some cases than
> opAdd.  For example, in some cases opAdd might require copying of a whole
> bunch of stuff, where opInc or opAddAssign just increments a single
> primitive under the hood.

I've always thought properties should work somewhat like this:

property int length {
    get() { return this.len; }
    set(newLen) { this.len = newLen; }
}

The return-type of get is automatically int, as is the parameter-type of
set. These two functions are automatically called when the property is
used.

int a = length;
// int a = length.get();

length = 10;
// length.set(10);

In cases where read/write access is needed, the compiler can do this:

length++;
// int temp = length.get();
// temp++;
// length.set(temp);

This can work for any user-defined type, since we're using the same
operator. If you want it done faster 'under the hood', you can use
operator-overloads inside the property:

property int length {
    get() { return this.len; }
    set(newLen) { this.len = newLen; }
    void opIncrement() { this.len++; }
}

-- 
Michiel




More information about the Digitalmars-d mailing list