[英]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.
我对此的平庸理解是 enum 是一种偏序。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.