If we have an enum class like this
enum class alpha{ a, b, c, d};
Is it possible to implement an operator that establishes an ordering relationship between the letters in the alphabet such that
enum class alpha{ a, b, c, d};
constexpr auto operator <=> (alpha lhs, alpha rhs)
{
//how do we achieve this?
};
#include <gtest/gtest.h>
TEST(alphabet, allows_ordering_comparison)
{
EXPECT_TRUE(alpha::a < alpha::b);
}
a less than comparison would evaluate to true. My mediocre understanding of this is that enum is a partial ordering. apologies for errors in the code. consider the question instead
You don't have to do anything. The language provides a <=>
for you that does the right thing already (assuming your enumerators are in order):
enum class alpha{ a, b, c, d};
static_assert(alpha::a < alpha::b);
static_assert(alpha::a <=> alpha::b < 0);
If you really wanted to, for whatever reason, you could manually provide one that does the same thing that the language does for you: compare the underlying values:
constexpr auto operator<=>(alpha lhs, alpha rhs)
{
using T = std::underlying_type_t<alpha>;
return T(lhs) <=> T(rhs);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With