简体   繁体   English

是否可以在 c++20 中使用比较运算符在枚举值之间建立小于大于顺序的关系

[英]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.

相关问题 在评估中使用多个“大于/小于”比较器是否合适? - Is it proper to use multiple 'greater-than / less-than' comparators in an evaluation? 对字符串使用小于比较运算符 - Using the less than comparison operator for strings 为什么 std::sort 在比较函数使用大于 (&gt;) 而不是大于或等于 (&gt;=) 时起作用? - Why does std::sort work when the comparison function uses greater-than (>), but not greater-than-or-equal (>=)? 为什么我的小于运算符没有处理? - Why isn't my less-than operator processing? 与三值比较函数相比,仅使用小于运算符进行排序 - Sorting only using the less-than operator compared to a trivalue compare function Apple clang 和 C++20 运算符歧义与继承的比较运算符 - Apple clang and C++20 operator ambiguity with inherited comparison operator 当匹配计数大于某个阈值时,我可以使用 C++20 范围来中断吗? - Can I use C++20 ranges to break when matched count is greater than some threshold? c ++ 20三路比较运算符的等效和相等之间的区别? - Difference between equivalent and equal for c++20 three way comparison operator? C++20 比较:关于不明确的反向运算符的警告 - C++20 comparison: warning about ambiguous reversed operator c++20默认比较运算符和空基class - c++20 default comparison operator and empty base class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM