std::less (and other related types like std::greater_equal, etc) is implemented in the following way: * if `operator<(T, U)` is defined for the argument types, it is called. * otherwise, if the argument types are convertible to `const volatile void *`, such conversion is performed, and it boils down to comparing the pointers. Now, assume a type which has an `operator const void *() const`, and provides `operator==()` and `operator<=>()` to generate all relational operators, the same way the std types do. So std::less will not use `operator<=>()`, but cast to `const void *` and compare pointers. This is wrong, because `operator<=>()` implies all relational operators, so it can be used to do the proper comparison. libc++ gets this right: // https://godbolt.org/z/E55eeosP9 // Courtesy of Ivan Solovev <ivan.solovev@qt.io> #include <compare> #include <functional> #include <iostream> struct S { int val; S(int v) : val(v) {} operator const void *() const { std::cout << "cast\n"; return &val; } friend bool operator==(S lhs, S rhs) noexcept { std::cout << "op==\n"; return lhs.val == rhs.val; } friend std::strong_ordering operator<=>(S lhs, S rhs) noexcept { std::cout << "op<=>\n"; return lhs.val <=> rhs.val; } }; int main() { const S arr[] = {S{2}, S{1}}; // In C++20 mode it compares pointers, and so considers that arr[1] > arr[0], // which is wrong! return std::greater_equal<>{}(arr[0], arr[1]) ? 0 : 1; }
It's only the C++14 "diamond"/is_transparent version of std::less/greater_equal that is affected. If you replace the return from main with greater_equal<S>{}, then it calls op<=>, too: // https://godbolt.org/z/cnjssh3ss return std::greater_equal<S>{}(arr[0], arr[1]) ? 0 : 1; // ^ added
Without looking at the code, we probably just need to check if the type has a usable operator<=>. We check it out had a usable operator< which worked fine in C++17, but in C++20 x<y can work without having any operator<
(In reply to Jonathan Wakely from comment #2) > Without looking at the code, we probably just need to check if the type has > a usable operator<=>. > > We check it out had Sorry, phone typos. "We check if it has..." > a usable operator< which worked fine in C++17, but in > C++20 x<y can work without having any operator<
Created attachment 57577 [details] Check for <=> Something like this (but it's also needed for std::greater and std::less_equal)
P2825 would be very useful here.