Best way to compare primitive types

Jari-Matti Mäkelä jmjmak at utu.fi.invalid
Tue May 8 05:58:23 PDT 2007


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.

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