Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
Fedor Avatar asked Sep 05 '21 12:09

Fedor


People also ask

How do you define comparison operators?

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.

How do you define a comparison operator in C++?

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.

Can comparison operator be overloaded?

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.


Video Answer


1 Answers

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

like image 174
Language Lawyer Avatar answered Oct 29 '22 00:10

Language Lawyer