A fresh look at comparisons

Janice Caron caron800 at googlemail.com
Mon Apr 14 02:40:56 PDT 2008


On 14/04/2008, Henning Hasemann <hhasemann at web.de> wrote:
>  What about this (much more primitive) approach:

One of the reasons that I believe comparison is "special", like
constructors, is because of the following:

    class A
    {
        int opEquals(Object o)
        {
           ...
        }

        int opCmp(Object o)
        {
           ...
        }
    }

    class B :A
    {
        int n;
    }

Hopefully, you can see the problem here immediately. B extends A, but
B does not provide opEquals nor opCmp, so if two Bs are compared, A's
compare functions will be called, which means that B's member n will
be ignored.

This is, of course, absolutely normal behavior for classes. It's how
inheritance works. But it's just not right for comparisons.

And important part of my proposal is that comparisons don't inherit.
Instead, we have the default behaviors that I described. Thus, under
my proposal, if B did not provide an is(this == c), then a default
implementation would be provided by the compiler, equivalent to

        is(this == c)
        {
            return super == c.super && n == c.n;
        }

This is very different from just changing the signature of a function.

Also, there really isn't any need for any comparison result to be
undefined. If (a < b) is not meaningful, it should suffice for (a < b)
and (b < a) both to return false. That's because less-than really is a
boolean question. If I ask "is a less than b?", and ordering is not
defined for that type, then it seems to me that "no" is the right
answer. (No, a is not less than b, because a and be cannot be
ordered). It is far, far less complicated that way - less-than is a
boolean question, not a yes/no/maybe question. However, what you /do/
need to lose, is the assumption that (a < b) implies (a !>= b),
because that no longer holds.



More information about the Digitalmars-d mailing list