Hi Steve!
On Friday, 9 June 2017 at 15:12:42 UTC, Steven Schveighoffer
wrote:
TypeInfo can provide the comparison for you, but it's a little
ugly.
If we take a look at std.algorithm.comparison.cmp, it uses
operators to compare two values (i.e. < first, then >,
otherwise return 0). However, this is less performant if the
type defines opCmp (you are calling it twice).
Calling opCmp twice on the same data is exactly what I tried to
avoid.
There really ought to be an opCmp for any type, which does the
best thing available. I'm not sure if it exists.
I agree it should exist.
If I were to write it, it would be something like:
int doCmp(T)(auto ref T t1, auto ref T t2)
{
static if(is(typeof(t1.opCmp(t2))))
return t1.opCmp(t2);
else
{
if(t1 < t2) return -1;
else if(t1 > t2) return 1;
return 0;
}
}
Then your function would work, just use doCmp instead of opCmp.
Thanks. That's working.
Do you know whether this will always generate optimally efficient
code (say, T is int and there is hardware support for three way
comparison)?
Note that D already (I think) does by default a member-wise
comparison, in order of declaration. So if that's all you
really need, I don't think you need to define opCmp at all.
Checked that:
Error: need member function opCmp() for struct Pair!(int, int) to
compare