www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Compare helper functions for writing opCmps

reply Bill Baxter <dnewsgroup billbaxter.com> writes:
Often an opCmp implementation will end up just being a comparison based 
on a single member of elementary type.

Is there any function in Phobos for doing an opCmp style comparison of 
the basic types?  Something like

int compare(S,T)(S a, T b) {
     if (a==b) return 0;
     return (a<b)? -1 : 1;
}

It's simple but comes up enough that it seems like it would be useful to 
have in the library.  Kinda like min/max.... which aren't in Phobos either.

-bb
Aug 28 2007
parent Downs <default_357-line yahoo.de> writes:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Bill Baxter wrote:
 Often an opCmp implementation will end up just being a comparison based
 on a single member of elementary type.
 
 Is there any function in Phobos for doing an opCmp style comparison of
 the basic types?  Something like
 
 int compare(S,T)(S a, T b) {
     if (a==b) return 0;
     return (a<b)? -1 : 1;
 }
 
 It's simple but comes up enough that it seems like it would be useful to
 have in the library.  Kinda like min/max.... which aren't in Phobos either.
 
 -bb
You can use typeinfo-based comparisons. return typeid(typeof(a)).compare(&a, &b); // ... I think I'm not sure if this actually works, but it should. Only good for comparing the same type though - otherwise we're stuck with what you proposed. And I agree, things like your code should be in the library. --downs -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFG1PgtpEPJRr05fBERAkb7AJ41+l/gwnVmx/d65VPCPOl9CDM//wCeLtC2 NKTlwjEb4ppKj851HtFkyvk= =802Q -----END PGP SIGNATURE-----
Aug 28 2007