C++20 is introducing a new comparison type: std::weak_ordering.
It allows for representing less than, equal to, or greater than.
However, some older functions use an int for a similar purpose. Such as qsort, which uses the signature
int compar (const void* p1, const void* p2);
How can I cast std::weak_ordering to int for the use in a function such as qsort?
Here is an example situation:
#include <compare>
#include <iostream>
int main() {
long a = 2354, b = 1234;
std::weak_ordering cmp = a <=> b;
if (cmp > 0) std::cout << "a is greater than b" << std::endl;
if (cmp == 0) std::cout << "a is equal to b" << std::endl;
if (cmp < 0) std::cout << "a is less than b" << std::endl;
int equivalent_cmp = cmp; // errors
}
In testing, I noticed that using a reinterpret_cast to int8_t type does work, but I am not sure if this would be portable.
int equivalent_cmp = *(int8_t *)&cmp;
or equivalently,
int equivalent_cmp = *reinterpret_cast<int8_t*>(&cmp);
Is this safe?
Furthermore, there are some other solutions that can work, but are inefficient compared this "unsafe" method. All of these would be slower than the above solutions
int equivalent_cmp = (a > b) - (a < b);
or
int equivalent_cmp;
if (cmp < 0) equivalent_cmp = -1;
else if (cmp == 0) equivalent_cmp = 0;
else equivalent_cmp = 1;
Is there a better solution that would be guaranteed to work?