C++20 comparison: warning about ambiguous reversed operator

前端 未结 2 2190
谎友^
谎友^ 2021-02-19 06:52

Consider this valid C++17 example:

struct A {
   bool operator==(const A&);
};


int main() {
   return A{} == A{};
}

When compiled in clan

2条回答
  •  生来不讨喜
    2021-02-19 07:28

    Does this warning mean that C++20 disallows using a typical comparison operator to compare two objects of the same type? What is the correct alternative? Is the situation expected to change in future drafts?

    This isn't really a typical comparison operator, it's already kind of wrong - since it only allows a const object on one side (your type A wouldn't satisfy the new equality_comparable concept either, even without any langauge changes).

    You have to write it this way:

    struct A {
       bool operator==(const A&) const;
    //                          ^^^^^^
    };
    

    This is the final rule for C++20.


    The specific issue is that in C++20, comparison operators add a new notion of rewritten and reversed candidates. So lookup for the expression a == b will also end up matching operators like b == a. In the typical case, this means you have to write fewer operators, since we know equality is commutative.

    But if you have a const-mismatch, what happens is you end up with these two candidates:

    bool operator==(/* this*/ A&, A const&); // member function
    bool operator==(A const&, /* this*/ A&); // reversed member function
    

    With two arguments of type A. The first candidate is better in the first argument, and the second candidate is better in the second argument. Neither candidate is better than the other, hence ambiguous.

提交回复
热议问题