ref returns and properties
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Mon Jan 26 07:15:59 PST 2009
Jacob Carlborg wrote:
[on properties]
> What about this:
>
> class Host
> {
> property acquire release prop
> {
> T get();
> }
> }
>
> And then the compiler will automatically created the "acquire" and
> "release" methods.
>
> There could also be what I would like to call "property shortcuts" (ruby
> calls this attributes) like this:
>
> class Host
> {
> get acquire release T prop;
> get set T prop2;
> }
I was hoping I'd shield putative users from having to write verbose
code. Besides, there's one other issue I stumbled upon while working on
porting std.algorithm to ranges.
You can't really pass an entire property to a function. This furthers
the rift between properties and true fields. Consider:
struct A { int x; }
void foo(ref int n) { if (n == 0) n = 1; }
...
A obj;
foo(obj.x);
So when passing obj.x to foo, foo can read and write it no problem. But
if x is a property of A, it all falls apart: obj.x means just reading
the property, not getting the property with all of its get and set splendor.
How did this hit me in std.algorithm? Replace A with your range of
choice, x with head, and foo with swap. If head is implemented as a
property instead of a ref-returning function or a field, I can't swap
the heads of two ranges!! This limits how ranges can be implemented; I
was hoping to allow head as a property, but it looks like I can't. Same
goes about opIndex. If you define a random-access range, you can't
define opIndex and opIndexAssign. You must define opIndex to return a
reference. That's a bummer.
Andrei
More information about the Digitalmars-d
mailing list