A Fresh Look at Comparisons, Take 2

Janice Caron caron800 at googlemail.com
Fri Apr 18 09:31:51 PDT 2008


On 18/04/2008, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> Yes.  That is a choice of the great-great-great-...-grandchild of A's author
>  :)

Hmmm.

I think more bugs are likely to occur as a result of people forgetting
to supply opCmp() and having the wrong opCmp() called.



>  By not overriding opEquals or opCmp, he is saying that if you compare it
>  with something else, A's implementation is the one to use.

...or he might have just forgotten, and it could be a bug.


>  If he wanted to
>  specify that opCmp should be different he would have rewritten opCmp.

...an /obscure/ bug, no less. One that might be very hard to track down.



>  >>  You need to have opEquals in Object in order to support hashing.
>
> > Please could you elaborate, as I don't understand why this is so?
>
> A hashtable works by <snip>

None of which implies that you need opEquals /in Object/. It only
implies that you need it in any class that needs to do hashing. Again,
this is a perfect case for explicit.



> It cannot be detected at compile time:
>
>  class A
>  {
>    int opCmp(Object o){...}
>  }
>
>  class B: A
>  {
>    int opCmp(Object o)
>    { throw new UnOrderedException("cannot order B");}
>  }
>
>  void f(A a, Object o)
>  {
>    a < o; // can you tell at compile time whether a is a B or an A?
>  }

No. On that point, you're right - although the code would look like
thus under the new rules:

    class A
    {
        explicit int opCmp(explicit const(A) c) const {...}
    }

    class B : A
    {
        // no opCmp
    }

    void f(A a, A o)
    {
        if (a < o)...
    }

Hmmm. I guess it /would/ have to be a runtime exception after all. I
stand corrected on that point. (You're also the second person to point
out that error, so I guess there's a consensus there). OK, drop the
"compile-time" claims! :-)



More information about the Digitalmars-d mailing list