Using array.sort

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Jan 26 03:46:33 PST 2007


Chris Nicholson-Sauls wrote:
> Frits van Bommel wrote:
>> 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...
> 
> Granted.  :)  I was really just trying to be illustrative, not 
> neccessarily thorough. (Take a look at the /glaring/ error in my other 
> exmaple... which, in hindsight, probably should've been more 
> complete|correct than this one.  Oh well, that's what I get for posting 
> while half asleep.)
> 
> But you make a good point of the sort that belongs in a FAQ somewhere, 
> actually.  I've seen plenty of opCmp's defined along these lines in 
> other code.

I usually prefer to write my opCmp in this fashion:
     return typeid(T).compare(&this.member, &other.member);

(replace T by whatever type you're comparing, or even 
"typeof(this.member)" if you're afraid you might forget to change this 
code if you change the type of 'member')

That way I don't make any stupid or annoying mistakes...


More information about the Digitalmars-d-learn mailing list