@property ref foo() { ...} won't work...?

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Mar 1 04:19:21 PST 2011


On Tue, 01 Mar 2011 12:25:30 +0100, Magnus Lie Hetland wrote:

> In Andrei's book, as well as in the Phobos source, there are property
> getters that return refs, as in...
> 
>   @property ref T front() {
>       return _payload[0];
>   }
> 
> ... and code that uses this with simple assignments, such as:
> 
>   r.front = foo;
> 
> For some reason, I can't get this to work in my code :-/ DMD seems to
> insist that I add a setter as well (i.e., @property T front(T val) {
> return _payload[0] = val; }).
> 
> On the other hand, I *do* get
> 
>   r.front() = foo;
> 
> to work. That works well even without @property, of course; and r.front
> fails even without @property.
> 
> Then, again, if I write both the getter (front()) and the setter
> (front(T)), that works even without @property (which, then, seems rather
> redundant?).
> 
> So ... I guess I have two questions:
> 
> 1. What's the point of @property (when it seems I get the same
> functionality without it)?

That is because @property is a relatively new feature.  In D1, and until 
recently in D2, there was no such thing as @property.  The choice of 
whether to write

  x = s.foo();
  s.foo(x);

or

  x = s.foo;
  s.foo = x;

was completely up to the user.  The plan is for the compiler to enforce 
the first syntax for non- at property functions and the latter syntax for 
@property functions.  I believe the reason this hasn't been implemented 
yet is that it will break a *lot* of code, so people are currently 
getting a chance to update their code base before it breaks.


> 2. How can I make r.front = foo work, when I only have r.front(),
> returning a ref (which seems like it is used in actual code)?

I think this is a bug, but I'm not entirely sure.  Even though assignment 
doesn't work, this does:

  r.front++;

The same happens when you overload the indexing operator, []:

  struct S { ref int opIndex(int i) { ... } }

  S s;
  s[0]++;      // works
  s[0] = 123;  // fails

You have to define opIndexAssign() for the last line to work.

-Lars


More information about the Digitalmars-d-learn mailing list