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.
Comparison operators can compare numbers or strings and perform evaluations. Expressions that use comparison operators do not return a number value as do arithmetic expressions. Comparison expressions return either 1 , which represents true, or 0 , which represents false.
Comparison operators in C++ are the ones that are there to compare two values with each other such as “==”, “!= ”, “>”, “<”, “>=”, and “<=”. This article will share the methods of overloading all six of these comparison operators in C++ in Ubuntu 20.04.
You can overload any of these operators, which can be used to compare the objects of a class. Following example explains how a < operator can be overloaded and similar way you can overload other relational operators.
P2085R0 removed the requirement on the defaulted comparison operator to be defaulted on the first declaration. Clang currently doesn't support this proposal:
See also https://reviews.llvm.org/D103929
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With