Best way to compare primitive types
John Ohno
john.ohno at gmail.com
Tue May 8 09:55:41 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
> }
> }
You could probably cast to a void[] and opcmp that. Depends on whether you want to compare by value or by pointer.
This should work:
int opCmp!(T)(T o1, T o2) {
return ((*(cast(void[]*)(cast(void*)o1)))==(*(cast(void[]*)(cast(void*)o2))));
}
It should work for any type, primitive or otherwise.
More information about the Digitalmars-d-learn
mailing list