A fresh look at comparisons

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 16 07:18:53 PDT 2008


"Yigal Chripun" wrote
> After reading the documentation for operator overloading I think there
> is a much simpler solution to this problem. have a look at the
> definition of Object in phobos - it contains opEquals and opCmp and
> that's it. No other opSomthing are defined there.
>
> So basically, I propose just removing those two operators from Object.
>
> if opEquals is not defined for the specific object than the compiler
> should default to identity comparison (as if you've used "is"),
> otherwise it'll use the defined method and return bool.

In fact, that is the default implementation of opEquals in Object :)

> if opCmp is not defined than the compiler will issue an error for trying
> to compare incomparable types.  otherwise, let it work the same as today.

I agree with you on this, but I think it can be solved without changing the 
compiler.

The default opCmp today is:

int opCmp(Object o) { return this !is o;}

Which I think is very incorrect.  If you are depending on opCmp being a 
well-defined order, for instance, in order to sort data, then your code may 
incorrectly assume that it can sort any object type.  IMO, opCmp should be 
defined in an interface, and those classes which implement it should 
implement that interface.  This would prevent trying to compare something 
that doesn't implement the opCmp method.

-Steve 





More information about the Digitalmars-d mailing list