www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Dealing with property function and operator overloads

Sample code:

struct Point
{
    int x, y;

    void opOpAssign(string op)(int rhs)
    {
        mixin("x = x " ~ op ~ " rhs;");
        mixin("y = y " ~ op ~ " rhs;");
    }
}

struct Wrapper
{
    void notifyChanged() { }
     property void point(Point newpoint) { _p = newpoint; notifyChanged(); }
     property Point point() { return _p; }

    private Point _p;
}

void main()
{
    auto wrap = Wrapper();
    wrap.point = Point(1, 1);
    assert(wrap.point == Point(1, 1));

    wrap.point += 1;
    assert(wrap.point != Point(2, 2));  // oops
}

I want to get notified when the _p field is changed. A property
function works for assignments, but by using property functions I lose
any operator overloads Point might have.

I was thinking I could provide some sort of injecting mechanism into
the Point definition, so I could get rid of property functions and
instead do something like this:

struct Wrapper
{
    this(...)
    {
        point.changed = &notifyChanged;
    }
    public Point point;
}

Has anyone ran into this issue before, and if so how did you work around it?
Oct 03 2011