简体   繁体   English

为简单结构定义飞船操作符

[英]Define spaceship operator for simple struct

I am trying to explicitly implement the spaceship operator.我正在尝试明确实施宇宙飞船运营商。

The following is a simple example which fails.以下是一个失败的简单示例。 What am I doing wrong?我究竟做错了什么? godbolt link神栓链接

#include <iostream>

struct Foo {
    int value;

    // both work
    auto operator<=>(const Foo&) const = default;
    //bool operator==(const Foo other) const { return value == other.value; }

    // both fail
    // auto operator<=>(const Foo& other) const { return value <=> other.value; }
    // auto operator<=>(const Foo other) const { return value <=> other.value; }
};

// fails
//auto operator<=>(const Foo lhs, const Foo rhs) { return lhs.value <=> rhs.value; }

int main(){
    Foo x{0};
    std::cout << (x == x) << '\n';
}

operator<=> does not actually implement the == operator. operator<=>实际上并没有实现==运算符。 operator== must be defined separately from operator<=> . operator==必须与operator<=>分开定义。 So, you need to define operator== as well.因此,您还需要定义operator==

The reason is that it's quite often possible to implement == more efficiently than <=> .原因是==的实现往往比<=>更有效。

As per @Silvio Mayolo's link: https://en.cppreference.com/w/cpp/language/default_comparisons根据@Silvio Mayolo 的链接: https ://en.cppreference.com/w/cpp/language/default_comparisons

If operator<=> is defaulted and operator== is not declared at all, then operator== is implicitly defaulted.如果 operator<=> 是默认的并且 operator== 根本没有声明,那么 operator== 是隐式默认的。

Therefore in this definition:因此在这个定义中:

auto operator<=>(const Foo& other) const { return value <=> other.value; }

operator== won't be implicitly declared, hence the compiler error. operator==不会被隐式声明,因此编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM