[Issue 1124] inconsistent: "<" calls opCmp(typeof(this) o); but array.sort calls opCmp(Object o)

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Sep 29 05:31:52 PDT 2007


http://d.puremagic.com/issues/show_bug.cgi?id=1124


smjg at iname.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |smjg at iname.com




------- Comment #1 from smjg at iname.com  2007-09-29 07:31 -------
That array.sort calls opCmp(Object) is as documented:

http://www.digitalmars.com/d/1.0/arrays.html
"For the .sort property to work on arrays of class objects, the class
definition must define the function: int opCmp(Object). This is used to
determine the ordering of the class objects. Note that the parameter is of type
Object, not the type of the class."

However, this itself seems to be due to Walter's aversion to implementing such
features as this using templates.

That relational operators call opCmp(typeof(this) o) is a little inaccurate -
actually they call opCmp(typeof(that) o).  But this is sensible.  If both
methods exist, then they would have to be equivalent to make sense, likely by
this idiom:

class Qwert {
    int opCmp(Object o) {
        return opCmp(cast(Qwert) o);
    }

    int opCmp(Qwert q) {
        ...
    }
}

In this case, why take the performance hit of a runtime cast if it's known at
compile time that the RHS is a Qwert?

This becomes even more significant if the class is comparable with more than
one other class, and you need different code to implement each.  Then you'd
need something like

class Qwert {
    int opCmp(Object o) {
        if (cast(Qwert) o) return opCmp(cast(Qwert) o);
        if (cast(Yuiop) o) return opCmp(cast(Yuiop) o);
        assert (false);
    }

    int opCmp(Qwert q) {
        ...
    }

    int opCmp(Yuiop y) {
        ...
    }
}

The compiler won't necessarily inline the opCmp(Object) call.  So cutting out
the middleman really is the right thing.


-- 



More information about the Digitalmars-d-bugs mailing list