How to implement opCmp?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 13 07:51:40 PDT 2017


On 6/11/17 11:24 AM, Honey wrote:
> On Friday, 9 June 2017 at 17:50:28 UTC, Honey wrote:
>> Looking at the implementation of Tuple.opCmp, I'm not sure I'd bet on
>> existence of opCmp for fundamental types:
>>
>>         int opCmp(R)(R rhs)
>>         if (areCompatibleTuples!(typeof(this), R, "<"))
>>         {
>>             foreach (i, Unused; Types)
>>             {
>>                 if (field[i] != rhs.field[i])
>>                 {
>>                     return field[i] < rhs.field[i] ? -1 : 1;
>>                 }
>>             }
>>             return 0;
>>         }
>
> It turned out that there is a standard three way comparison function for
> ranges and strings [1].

Yes, I saw that when I was looking (you can see from my reply that you 
quoted below).

> Doesn't it make sense to introduce another overload of cmp similar to
> Steve's doCmp [2] right at that spot?

Yes I think it makes sense to have such a comparison function for 
non-ranges. Yes it probably belongs there, as there are other functions 
(e.g. swap) that are not specific to ranges in std.algorithm. It should 
probably not be called cmp, as it will be a default comparison (with the 
default ordering), although if we did something like:

int cmp(alias pred = "a < b", T)(T t1, T t2) if(!isInputRange!T)
{
    static if(pred == "a < b") { /* do default optimized way */ }
    else { /* more generic mechanism using pred */ }
}

it might be nice. Need to think about the API ramifications.

> This would simplify the implementation of opCmp for aggregates and can
> also lead to a moderate performance benefit [3]. (Note that [3] does not
> provide an additional overload of cmp but uses a less elegant approach
> with the same performance characteristics.)

I agree. It's a thing also that can be optimized in unintuitive ways. I 
think Andrei has a nice way to do opCmp for integers that's a simple 
subtraction and negation or something like that.

-Steve


More information about the Digitalmars-d-learn mailing list