Best way to compare primitive types

Don Clugston dac at nospam.com.au
Tue May 8 06:31:19 PDT 2007


Jari-Matti Mäkelä wrote:
> Daniel Keep wrote:
>> Jari-Matti Mäkelä wrote:
>>> Let's say I want to write a wrapper around a primitive type (it could
>>> possibly also be a class or struct, but that isn't necessary now). What's
>>> the best way to do opCmp?
> 
>> I imagine if you wanted to do it *properly*, you could write a templated 
>> compare function that uses static ifs to do comparison of atomic
>> numeric types, arrays of (sometype), aas of (sometype, sometype),
>> structs, classes, typedefs and pointers to (sometype).
> 
> 
>> Or, you could just cheat.
>>
>> int opCmp(T other)
>> {
>>     if( other < this ) return -1;
>>     else if( this < other ) return 1;
>>     else if( this == other ) return 0;
>>     else assert(false); // you COULD get here if other is NaN
>> }
> 
> Thanks for all the answers.
> 
> Actually this is almost the same I have now. I just created another version
> of opCmp for types that have a NaN value and made them return NaN, not
> assert.

Since there is no opUnordered(), (you can't have !<>= for UDTs) it's 
hard to know what to do with a NaN -- I don't think it's possible to 
make it work sensibly. It's inevitable that it will be different to the 
built-in operators.

> Ok, I think your reply also answers my question about the builtin comparison
> functionality. So there isn't currently one. Wouldn't it be useful to get
> a "properly" done templated version into the "standard library"?


More information about the Digitalmars-d-learn mailing list