Best way to compare primitive types

Ary Manzana ary at esperanto.org.ar
Tue May 8 05:43:28 PDT 2007


Maybe something like this:
---
int opCmp(T other) {
     return this.value > other ? 1 :
         (this.value < other ? -1 : 0);
}
---

Usage:
---
void main() {
	Foo!(int) f1;
	f1.value = 5;
	
	writefln("%s", f1 < 6);
	writefln("%s", f1 > 6);
}
---

Ouputs:
true
false

Note that for equals comparison you need to implement opEquals (I didn't 
know that until I wrote the example... isn't it a bit akward?).

Jari-Matti Mäkelä escribió:
> 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
>         }
> }


More information about the Digitalmars-d-learn mailing list