Using array.sort

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Thu Jan 25 03:07:32 PST 2007


Chris Nicholson-Sauls wrote:
> class Number {
>   int i;
> 
>   int opCmp (Object obj) {
>     if (auto other = cast(Number) obj) {
>       return this.i - other.i;
>     }
>     else {
>       throw new Exception("Can only compare Number with another Number.");
>     }
>   }
> }

Broken. (int.max - int.min) doesn't fit in an int...
This is a valid implementation only when the range is less than about 
half that of an int. In practice, that means this is a valid 
implementation if member 'i' is a bool, byte, ubyte, short, ushort, char 
or wchar, but not if it's an int, uint, long or ulong. Nor will it be 
correct for cent and ucent when they get implemented.
Any built-in type not mentioned don't work. (unless I missed any ;) )
Well, theoretically, on a machine with an address space of 31 bits or 
less it would also work for pointers on that machine...

A generic way to do it would be something like
   return typeid(i).compare(&i, &other.i);
That should always return a valid value for built-in types and arrays, 
and call opCmp for user-defined types[1].


[1]: With some wrapping. nulls are always considered 'less than', and 
structs without opCmp members default to calling memcmp instead.


More information about the Digitalmars-d-learn mailing list