C++20 comparison: warning about ambiguous reversed operator

前端 未结 2 2194
谎友^
谎友^ 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

    It is a general rule of overload resolution that each argument type must be separately at least as close to the parameter type for a selected function as to the parameter type for any other:

    struct A {A(int);};
    void f(long,int);   // #1
    void f(int,A);      // #2
    void g() {f(0,0);}  // error: ambiguous
    

    The much worse conversion for the second argument for #2 doesn’t make up for the intlong conversion on the first argument.

    In C++20, various rewrite rules have been added to obviate the need to write so many all-but-identical comparison operator overloads. While the trivial ambiguities between hand-written “reversed candidates” and identical compiler-generated ones are handled by tie-breaker rules that prefer real functions, that’s (again) not enough to make up for a worse conversion for any argument.

    Comparison operators written carefully according to accepted (C++17) practices will very rarely run afoul of this, but questionable signatures like this (with asymmetric const) may very well be problematic (in new ways). Hopefully more bugs are found than are caused by this extension.

提交回复
热议问题