Quantcast
Channel: Is the three-way comparison operator always efficient? - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Is the three-way comparison operator always efficient?

$
0
0

Herb Sutter, in his proposal for the "spaceship" operator (section 2.2.2, bottom of page 12), says:

Basing everything on <=> and its return type: This model has major advantages, some unique to this proposal compared to previous proposals for C++ and the capabilities of other languages:

[...]

(6) Efficiency, including finally achieving zero-overhead abstraction for comparisons: The vast majority of comparisons are always single-pass. The only exception is generated <= and >= in the case of types that support both partial ordering and equality. For <, single-pass is essential to achieve the zero-overhead principle to avoid repeating equality comparisons, such as for struct Employee { string name; /*more members*/ }; used in struct Outer { Employeee; /*more members*/ };– today’s comparisons violates zero-overhead abstraction because operator< on Outer performs redundant equality comparisons, because it performs if (e != that.e) return e < that.e; which traverses the equal prefix ofe.name twice (and if the name is equal, traverses the equal prefixes of other members of Employee twice as well), and this cannot be optimized away in general. As Kamiński notes, zero-overhead abstraction is a pillar of C++, and achieving it for comparisons for the first time is a significant advantage of this design based on <=>.

But then he gives this example (section 1.4.5, page 6):

class PersonInFamilyTree { // ...public:  std::partial_ordering operator<=>(const PersonInFamilyTree& that) const {    if (this->is_the_same_person_as ( that)) return partial_ordering::equivalent;    if (this->is_transitive_child_of( that)) return partial_ordering::less;    if (that. is_transitive_child_of(*this)) return partial_ordering::greater;    return partial_ordering::unordered;  }  // ... other functions, but no other comparisons ...};

Would define operator>(a,b) as a<=>b > 0 not lead to large overhead? (though in a different form than he discusses). That code would first test for equality, then for less, and finally for greater, rather than only and directly testing for greater.

Am I missing something here?


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images