我正在寻找一种实现三向比较运算符和 operator == 的方法:
class Foo
{
public:
auto operator<=>( const Foo& rhs ) const noexcept = default;
private:
std::uint32_t m_Y;
std::uint32_t m_X;
char m_C;
std::vector<char> m_Vec;
};
但是 default
实现不是我的意图。因此,我需要编写自己的实现。
我想要的是:
- 我想要 equality 比较(
==
和!=
)基于比较成员 m_y < /code>, m_x
和 M_C
两个操作数(类型 foo
)。所有这三个成员必须等于满足平等。 m_vec
内容的平等并不重要(因为在词典上比较所有这些元素并不有效)。
- 我希望订购比较(
&lt;
和&gt;
)基于比较表达式 m_y
* m_x
。
- 我希望订购比较(
&lt; =
and &gt; =
)基于比较表达式 m_y < /code> * m_x
,如果两个操作数在这方面相等,则两个操作数的所有三个成员都应等于满足&lt; =
或&gt; =
(就像 ==
中的一样)。
另外,所有这些比较类别类型都更适合此方案, std :: strong_ordering
或 std :: feek_ordering
?
我应该如何实施这种逻辑?看起来很简单,我在C ++ 20书中读了整个食谱,但我仍然无法弄清楚。
I'm looking for a way to implement the three-way comparison operator and the operator== for the following class:
class Foo
{
public:
auto operator<=>( const Foo& rhs ) const noexcept = default;
private:
std::uint32_t m_Y;
std::uint32_t m_X;
char m_C;
std::vector<char> m_Vec;
};
But the default
implementation is not what I intended. Therefore I need to write my own implementation.
What I want is:
- I want the equality comparison (
==
and !=
) to be based on comparing the members m_Y
, m_X
, and m_C
of two operands (of type Foo
). All of those three members must be equal to satisfy the equality. The equality of the content of m_Vec
is not important (since it's not efficient to compare all those elements lexicographically).
- I want the ordering comparison (
<
and >
) to be based on comparing the expression m_Y
* m_X
.
- I want the ordering comparison (
<=
and >=
) to be based on comparing the expression m_Y
* m_X
and if both operands are equal in that regard, then all three members of both operands should be equal to satisfy the <=
or >=
(just like in ==
).
Also with all this said, which comparison category type suits this scenario better, std::strong_ordering
or std::weak_ordering
?
How should I implement such logic? It seems simple and I read a whole recipe in a C++20 book on this topic and I still can't figure it out.
我相信这是一个偏序,即元素可能无法比较的顺序(
<
、>
或==
都不是)夹在他们之间)。您应该验证必要的定律成立 (a <= b
iffa < b || a == b
,a <= a
> 对于所有a
,a == b
如果对于所有a <= b &&b <= a
a、b
和a <= c
如果a <= b && b <= c
对于所有a
、b< /代码>,<代码>c)。如果是这种情况,请使用
std::partial_ordering
。I believe this is a partial order, which is an order where elements may be incomparable (none of
<
,>
, or==
hold between them). You should verify the necessary laws hold (a <= b
iffa < b || a == b
,a <= a
for alla
,a == b
ifa <= b && b <= a
for alla
,b
, anda <= c
ifa <= b && b <= c
for alla
,b
,c
). If that is the case, usestd::partial_ordering
.