Problem with Point property
Chris Nicholson-Sauls
ibisbasenji at gmail.com
Wed Mar 7 13:31:36 PST 2007
Henning Hasemann wrote:
> 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
>
Actually, that's rather slick, and worth studying, even if it turns out not to be optimal.
(Which with a significant number of such properties, it couldn't possibly be.) I really
can't offer anything better off hand.
-- Chris Nicholson-Sauls
More information about the Digitalmars-d
mailing list