Explicit call of ternary compare

Simen Kjaeraas simen.kjaras at gmail.com
Mon Jul 23 08:36:57 PDT 2012


On Mon, 23 Jul 2012 16:32:15 +0200, monarch_dodra <monarchdodra at gmail.com>  
wrote:

> Is there any (efficient and correct) way to do ternary comparison on two  
> objects?
>
> You know the:
> ----
> if(a<b) return -1;
> if(b<a) return 1;
> return 0;
> ----
>
> I'm using the above method in a template, and the problem is that if a  
> or b is a struct/class, this will resolve to 4 (!) calls to opCmp.
>

First, no. It will only call opCmp twice - once for each comparison.  
You're thinking of opEquals.

Second, have you tried a.opCmp(b), cause that's the logical thing to try,  
and it works.
Like other operator magic in D, it's not really magic. It's just a simple  
lowering of a < b to a.opCmp(b) < 0.
In other words, operator overload functions in D can be called just like  
regular functions:

auto o = a.opOpAssign!"it's the 'look ma' operator!"("a string", 42,  
!false); // Don't expect this to work unless you've explicitly designed it  
to.

-- 
Simen


More information about the Digitalmars-d-learn mailing list