C++ spaceship operator multilevel compare?
Asked Answered
N

1

6

Does the new C++20 spaceship operator allow a concise way of expressing short-circuited multiple-criteria comparison? Something better than this:

const firstCriteriaComparisonResult = lhs.x <=> rhs.x;
return firstCriteriaComparisonResult != 0 ? firstCriteriaComparisonResult : lhs.y <=> rhs.y;
Niels answered 18/5, 2021 at 4:29 Comment(3)
I was under the impression it automatically did a member-wise compare; cppreference says yes.Caruncle
That said, if you only want to compare one or two elements instead of all of them, just do the normal comparison overloads.Caruncle
Re comment 1: If operator<=>() member must be a template function (templated on RHS type) then it must be written by hand. Template opeators cannot be = defaulted. Re comment 2: there are no "normal comparison overloads" and there never were. Comparison overloading has always been a mess, and the three-way compare operator was added to the language precisely to address this issue.Comb
C
12

The usual tie-and-compare approach works with spaceship too:

return std::tie(lhs.x, lhs.y) <=> std::tie(rhs.x, rhs.y);
Cornell answered 18/5, 2021 at 4:51 Comment(1)
I honestly didn't know that one! I'm back to C++ after a decade, and std::tie() is apparently about that old.Comb

© 2022 - 2024 — McMap. All rights reserved.