Properties don't behave like variables?

Artur Skawina art.08.09 at gmail.com
Mon May 7 15:23:04 PDT 2012


> On 2012-05-07 21:53, Steven Schveighoffer wrote:
> 
>> How do you overload the operator for a property? For example:

It can of course be done [1], but i think the question was whether the
compiler should do the obvious rewrite from 'prop() |= 2' to 'prop(prop()|2)'.
Unconditionally, as not doing it every time would be confusing and lead
to bugs where the setter gets bypassed.
But what about the case where you want to return a ref to /different/
objects? I guess mandating a setter wouldn't be problem, and still better
than the alternative.

artur

[1] I shouldn't even be posting this, as someone might actually think about
using something like it...

   struct S {
      int i;
      @property ref p() { return *cast(PropProxy!(typeof(this),"i")*)&this; }
   }

   int main()
   {
      S s;
      s.p |= 2;
      return s.p;
   }

   struct PropProxy(RT, string sym) {
      @property ref data() { return *cast(RT*)&this; }
      @property ref get() { return __traits(getMember, data, sym); }
      alias get this;
      auto opOpAssign(string op, T)(T b) {
         return mixin("data." ~ sym ~ " " ~ op ~ "= b");
      }
   }

Keep in mind this isn't a serious suggestion, more of a joke; i wrote it just 
out of curiosity, to check if GDC would be able to turn it all into
"mov $0x2, %eax; ret;". ;)



More information about the Digitalmars-d mailing list