Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a less-than greater-than ordering relationship between enum values using comparison operator in c++20

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

like image 423
Aaron Chifwalo Shavesha Avatar asked Sep 16 '25 21:09

Aaron Chifwalo Shavesha


1 Answers

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);
}
like image 200
Barry Avatar answered Sep 18 '25 18:09

Barry