Problem with Point property

Henning Hasemann hhasemann at web.de
Wed Mar 7 04:46:15 PST 2007


I found a 'solution' myself which is aahh.. 'tricky'.
I extend the struct to be able to call the setter method
whenever its value changes.
To stop behaving it like a pointer, I misuse opCast as
a 'copy constructor'. So

Point p = (new Foo).position;
p.x = 5;

wont change the Foo's position, as it where when position was
a real member. 

Look here:

struct Point {
  private {
    int mX, mY;
    void delegate(Point) setter;
  }
  
  Point opCast() {
    Point p;
    p.setter = null;
    p.mX = x; p.mY = y;
    return p;
  }

  int x() {
    return mX;
  }
  void x(int x1) {
    mX = x1;
    if(setter !is null)
      setter(*this);
  }
  // skipped the same for y
}

To be used like:

class Bar {
  private Point mPosition;
  this() {
    mPosition.setter = &position;
  }
  Point position() {
    return mPosition;
  }
  void position(Point p) {
    mPosition = p;
  }
}

  Bar b;

  // This actually changes the object
  b.position.x = 7;
  writefln(b.position.x); // 7

  // This as before, does not
  Point p = b.position; // here opCast is being called
  p.x = 5;
  writefln(b.position.x); // still 7


The only thing is Im not quite sure if using opCast this way is
portable across versions and compiler manufracturers,
anyone knowing something about that?

Henning




  


-- 
v4sw7Yhw4ln0pr7Ock2/3ma7uLw5Xm0l6/7DGKi2e6t6ELNSTVXb7AHIMOen5a2Xs5Mr2g5ACPR hackerkey.com



More information about the Digitalmars-d mailing list