How do you reverse a strong_ordering?
Asked Answered
S

1

15

Is there an easier way to achieve the effect of this function?

strong_ordering reverse(strong_ordering v) {
    if (v > 0)
        return strong_ordering::less;
    else if (v < 0)
        return strong_ordering::greater;
    else
        return v;
}
Sophisticate answered 6/2, 2020 at 3:21 Comment(0)
S
17

Yep:

strong_ordering reverse(strong_ordering v)
{
    return 0 <=> v;
}

Which is literally specified as what you want:

Returns: v < 0 ? strong_­ordering​::​greater : v > 0 ? strong_­ordering​::​less : v.

This follows the general principle that x <=> y and y <=> x are opposites, and v <=> 0 is just an identity operation for v.

Simpatico answered 6/2, 2020 at 3:33 Comment(9)
Replacing the 0 with either strong_ordering::equal or strong_ordering::equivalent would also work, right?Jocose
i use the clang 11.0.0 compiler, and get a invalid operands to binary expression error. does the the compiler not support this feature yet?Sophisticate
@Sophisticate clang 10 isn't even released yet.... but both clang and gcc do support this on trunk: godbolt.org/z/kDQxFYSimpatico
@Jocose No, it would not. strong_ordering is not <=>-able with itself, only against 0.Simpatico
@Simpatico so strong_ordering doesn't have a strong ordering?Phagocytosis
@Phagocytosis Yeah, I don't really know that I want to go down the path of strong_ordering having a strong_ordering, weak_ordering having a strong_ordering, but partial_ordering having a partial_ordering, you know?Simpatico
@Barry: Good to know. It feels weird to compare special types to 0 if there is another option, but I guess there isn't. It's NULL all over again, whee!Jocose
error: invalid operands to binary expression ('std::__1::strong_ordering' and 'int')Sophisticate
@Sophisticate The compiler you're using probably doesn't support this, support for <=> is very recent. But as I showed earlier, trunk on both clang and gcc do support this now (but no official releases do yet).Simpatico

© 2022 - 2024 — McMap. All rights reserved.