Operators overloading in D2 again

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Mon May 3 09:46:41 PDT 2010


On Mon, 03 May 2010 14:28:20 +0000, Dan wrote:
> it certainly helps. However I can't help myself, I still thinking that
> this is the most complicated, hard read and to understand way to
> overload operators. Maybe there is something I'm missing but I can't
> really see the reason of all that. Other languages adopts a much easier
> approach, for example python but also C++ that D is trying to surpass
> (and it does in most cases) when it comes to operator overloading is
> much more clear than D.
> 
> I still thinking that the D1's approach was much better than this.

I was sceptic at first, too, but after having written some code using the 
new operator overloading system I am convinced:  It totally rocks.  It is 
amazing how much boilerplate code one *doesn't* have to write anymore.   
Here's a trivial example:

    struct Pair(T)
    {
        T a, b;

        Pair opBinary(string op)(Pair p)
        {
            auto r = this;
            r.opOpAssign!op(p);
            return r;
        }

        Pair opOpAssign(string op)(Pair p)
            if (op == "+=" || op == "-=" || op == "*=" || op == "/=")
        {
            mixin ("a "~op~" p.a");
            mixin ("b "~op~" p.b");
            return this;
        }
    }

With just two short function definitions I have written what would have 
been eight functions with the old system.  For real-life examples, check 
out:

http://www.dsource.org/projects/phobos/browser/trunk/phobos/std/bigint.d
http://www.dsource.org/projects/phobos/browser/trunk/phobos/std/complex.d


> Anyway, now I have another problem: I can't get how to overload
> operators like these <=, <, >=, >. I read the documentation but I can't
> really understand it.

Here's an example which (hopefully) illustrates how it works:

    // Simple struct that wraps a built-in integer.
    struct Integer
    {
        int n;
 
        int opCmp(Integer i)
        {
            // If this is smaller than i, return a negative number.
            if (n < i.n) return -1;
 
            // If this is equal to i, return zero.
            else if (n == i.n) return 0;

            // If this is greater than i, return a positive number.
            else return 1;
        }
    }

Of course, this was a needlessly verbose example, as I could just have 
written this instead:

   int opCmp(Integer i) { return n - i.n; }

This, I guess, is why the signature of opCmp() is the way it is.

-Lars


More information about the Digitalmars-d-learn mailing list