How to implement opCmp?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 9 10:28:18 PDT 2017
On 6/9/17 11:33 AM, Honey wrote:
> Hi Steve!
>
> On Friday, 9 June 2017 at 15:12:42 UTC, Steven Schveighoffer wrote:
>> 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)?
No, I don't know. I wrote it in about 10 seconds on the forum :) I'm
sure there's better ways to compare integers than that.
This is why I think such a function should exist in Phobos/druntime. I'm
not 100% sure it doesn't already, but I couldn't find one...
>> 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
OK, maybe it's just equality and hashing then. Sorry for the noise.
-Steve
More information about the Digitalmars-d-learn
mailing list