Best way to compare primitive types

Daniel Keep daniel.keep.lists at gmail.com
Tue May 8 05:40:50 PDT 2007



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've seen there is TypeInfo.compare there
> somewhere, but how does it work? I get
> 
>   Error: this for compare needs to be type TypeInfo not type Foo *
> 
> Also, if it works, does it have performance problems? I read from the ng
> archives that the compiler might not inline it.
> 
> Here's the stuff I'm writing:
> 
> struct Foo(T) {
>         T value;
> 
>         // or maybe T opCmp(T other) for reals, floats etc.
>         // to handle NaN properly
>         int opCmp(T other) {
>                 // I would like to do something like
> 
>                 // return builtin.opCmp(value, other.value);
> 
>                 // because there are so many special cases for
>                 // the primitive types and it feels a bit stupid
>                 // to reimplement the comparison in every wrapper
>         }
> }

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
}

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list