On Mon, 23 Jul 2012 16:32:15 +0200, monarch_dodra <[email protected]> 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

Reply via email to