operator== on C++ structs with conversion operators

huangapple go评论63阅读模式
英文:

operator== on C++ structs with conversion operators

问题

我试图理解当比较两个没有定义==操作符的结构体时所涉及的==操作符集合。在这种情况下,会使用int的内置操作符进行转换。然而,对于嵌套类来说,例如,如果Y包含一个定义了==操作符的类,这种方法就不起作用。这只适用于结构体可以无歧义地转换为内置类型的情况吗?

英文:

I'm trying to understand the set of == operators that are explored when comparing two structs where there is no operator == defined. In this case the built-in operator for ints is used for conversion. However this does not work for nested classes for example, i.e. if Y contained a class that defined an == operator. Is this only applicable when a struct can be converted to a built-in type unambiguously?

struct X {
    int x;
};

struct Y {
    int y;
    operator int() {
        return y;
    }
};

int main() {
//    bool val {X{} == X{}}; // does not compile
    bool val {Y{} == Y{}}; // works
}

答案1

得分: 2

以下是翻译好的部分:

类和结构体默认没有等于(或其他)运算符。您需要为您的实现重载所需的运算符并明确指定比较方式。

struct X {
    int x;

    bool operator==(const X& other) const { return x == other.x; }
    bool operator!=(const X& other) const { return y != other.x; }
    ...
};

对于每个比较运算符(==、!=、<、>、<=、>=),都是如此,除非您使用C++20,在C++20中,您可以指定默认的<=>运算符,并让编译器为您生成它们(当然,您的结构体成员越多,这个过程就越复杂;关于比较的文档是很好的阅读材料)。

#include <compare>

struct X {
    int x;

    auto operator<=>(const X&) const = default;
};
英文:

Classes and structs don't have equality (or any) operators by default. You need to overload whatever is needed for your implementation and specify the comparisons explicitly.

struct X {
    int x;

    bool operator==(const X&amp; other) const { return x == other.x; }
    bool operator!=(const X&amp; other) const { return y != other.x; }
    ...

};

That's true for every comparison operator (==, !=, <, >, <=, >=). That is unless you use C++20, in which you can specify the default <=> operator and have the compiler generate them for you (ofc the more members your struct has, the more complicated this gets; the docs on comparisons are a good read).

#include &lt;compare&gt;

struct X {
    int x;

    auto operator&lt;=&gt;(const X&amp;) const = default;
};

huangapple
  • 本文由 发表于 2023年5月7日 06:08:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定