toHash /opCmp for builtin-types

Daniel Gibson metalcaedes at gmail.com
Mon Feb 21 12:22:13 PST 2011


Am 21.02.2011 20:59, schrieb Simon Buerger:
> Following came to my mind while coding some generic collection classes:
> The toHash and opCmp operations are not supported for builtin-types
> though their implementation is trivial.
>
> * toHash
> The code is already there inside TypeInfo.getHash. But
> typeid(value).getHash(&value) is much uglier than value.toHash. Note
> that hashes make sense for integer (trivial implementation), not
> necessarily for floats.
>
> * opCmp
> Would be useful for delegating opCmp of a struct to one member.
> Alternative: Introduce new operator which returns 1/0/-1 (ruby does this
> with "<=>"). Currently I end up writing:
>
> int opCmp(...)
> {
> if(a>b) return +1;
> if(a==b) return 0;
> return -1;
> }
>
> which uses 2 comparisons where only 1 is needed (though the compiler
> might notice it if comparision is pure and so on).
>
> Furthermore it might me a nice idea to have toString (or the future
> "writeTo") for builtin-types. It would need some new code in the
> core-lib, but could simplify generic programming.
>
> any thoughts?
>
> - Krox

Well, opCmp() can be done easier, at least for ints:

int opCmp(...) {
	return a-b;
}

For floats.. well, if you don't want/need any tolerance this would work 
as well, else it'd be more difficult.

A <=> operator would be neat, though.


More information about the Digitalmars-d mailing list