宇宙飞船运算符的定义意味着有一个强有力的排序定义,但这是否会影响客户端代码的编写方式,或者如何定义类比较操作符?
由于在另一篇文章中缺少真实世界的例子,我没有完全理解这个部分。
其他关于宇宙飞船操作员的帖子:
发布于 2019-01-23 04:05:15
<=>
允许懒惰的方式也是表演的方式。您不会更改客户端代码。
当存在using std::rel_ops
(或boost::ordered
等)时,客户端可能会看到性能方面的好处。
一个例子
// old and busted
struct Person : boost::totally_ordered<Person>
{
std::string firstname;
std::string lastname
bool operator<(const Person & other)
{
return std::tie(firstname, lastname)
< std::tie(other.firstname, other.lastname);
}
}
// new hotness
struct Person
{
std::string firstname;
std::string lastname;
auto operator<=>(const Person &) = default;
}
int main()
{
Person person1 { "John", "Smith" };
Person person2 { "John", "Smith" };
std::cout << person2 <= person1 << std::endl;
}
发布于 2019-01-23 05:35:30
你只需比较一下你一直以来的做法:
a < b
只是在幕后,该表达式的候选函数之一也会找到(a <=> b) < 0
,如果该候选函数存在并且恰好是最佳可行的候选函数,那么它就会被调用。
您通常不会在“客户端代码”中直接使用<=>
,只需直接使用所需的比较。
例如,考虑到:
struct X {
int i;
// this can be = default, just writing it out for clarity
strong_ordering operator<=>(X const& rhs) const { return i <=> rhs.i; }
};
表达式
X{42} < X{57};
将评估为X{42} <=> X{57} < 0
(没有<
候选,因此<=>
无反转是最合适的)。X{42} <=> X{57}
计算为42 <=> 57
,即strong_ordering::less
。< 0
返回true
。因此,最初的表达式是true
..。如预期的那样。
同样的运算符也直接给出了X{57} > X{42}
,X{3} >= X{2}
,等等。
<=>
的优点是您只需要编写一个操作符而不是四个操作符,该运算符通常比<
更容易编写,您可以正确地表示偏序和全序之间的区别,并且堆叠它通常具有更高的性能(例如,在string
这样的情况下)。
此外,我们不必生活在这个奇怪的世界里,每个人都假装operator<
是唯一存在的关系运算符。
https://stackoverflow.com/questions/54326473
复制