Property discussion wrap-up

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 29 10:52:12 PST 2013


On Tue, Jan 29, 2013 at 06:47:42PM +0100, Rob T wrote:
[...]
> The struct approach to implementing properties has a few major
> advantages.
> 
> One thing is that structs are already available and can do pretty
> much exactly what we want with properties, we just add
> specializations for use as a property.
> 
> Structs are made for wrapping up a data store into another one with
> functions for setting and getting and possibly doing other things,
> including storing additional state if required, so it's a lot more
> versatile than only a getter and setter with no additional state.
> 
> You can return a struct by reference, and the setter and getter will
> continue to work, you can also pass it by reference.
> 
> You can take the address of the struct property and use it
> correctly.
> 
> The "property as a function" approach cannot do these things without
> some crazy compiler magic.
> 
> The struct approach is neatly wrapped up into one self-contained
> package that is transportable.
> 
> The struct property concept is perhaps more profound than the
> function-only approach because it can be used for much more than
> what was originally intended, For example, any normal variable can
> be redefined into a property, allowing you to add additional state
> to it, and additional intelligence. Effectively, you are able to
> create "smart" variables and use them in a generalized way.
> 
> The property as a function approach, is not very profound, and the
> need for them is not very compelling, especially considering how
> much effort is being spend on this topic. The struct approach
> however is much more interesting and has much more potential use.
[...]

I agree with all of this, except that currently, as things stand, we
can't actually implement certain kinds of properties as structs, because
nested structs do not have access to their parent lexical scope:

	class Rectangle {
		float width, height;

		// Struct implementation of @property
		struct AreaProp {
			float value() {
				// Error: can't access Rectangle.width
				// and Rectangle.height
				return width*height;
			}
			alias value this;
			...
		}
		AreaProp area;
	}
	void main() {
		auto r = new Rectangle;
		r.width = 2.0;
		r.height = 1.5;
		writeln(r.area); // in theory, this should work
	}

We'd have to move width and height inside the AreaProp struct to make
this work, but then we're back to square one (you'd need @property to
implement .area inside AreaProp).


T

-- 
"I'm running Windows '98." "Yes." "My computer isn't working now." "Yes, you already said that." -- User-Friendly


More information about the Digitalmars-d mailing list