Search code examples
c++language-lawyerc++20comparison-operators

Can comparison operator be defaulted outside of class definition in C++20?


Starting from C++20, the compiler can automatically generate comparison operators for user classes by means of operator ==() = default syntax. But must this operator be defaulted only inside the class definition or can it be after the class definition as well?

Consider the program:

struct A { friend bool operator==(A,A); };
bool operator==(A,A) = default;

It is accepted by GCC, but rejected by Clang with the error:

error: equality comparison operator can only be defaulted in a class definition

Demo: https://gcc.godbolt.org/z/KboK7frhb

Which compiler is right here?

Putting operator definition outside of class definition can be useful for having the operator only in one translation unit, for example, thus improving compilation time of big program.


Solution

  • P2085R0 removed the requirement on the defaulted comparison operator to be defaulted on the first declaration. Clang currently doesn't support this proposal:https://clang.llvm.org/cxx_status.html

    See also https://reviews.llvm.org/D103929