其他分享
首页 > 其他分享> > c – 宇宙飞船操作符的实际使用示例[已关闭]

c – 宇宙飞船操作符的实际使用示例[已关闭]

作者:互联网

宇宙飞船操作符的定义意味着对排序有一个强烈的定义,但这是否会影响客户代码的方式或者如何定义类比较运算符?

由于在其他帖子中缺少现实世界的例子,我不完全理解这一部分.

关于宇宙飞船操作符的其他SO帖子:

> Spaceship comparison operator in C++
> What is the <=> operator in C++?
How and why did the ISO C++ Standards Committee (WG21) decide to accept the proposal for a spaceship operator as it is?
> How is the three-way comparison operator different from subtraction?

解决方法:

&LT =&GT允许懒惰的方式也是高效的方式.您不会更改您的客户端代码.

当使用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;
}

标签:c20,c,spaceship-operator
来源: https://codeday.me/bug/20190823/1697086.html