Consider the following struct with a single data member and an operator==
struct S {
int a;
/*constexpr*/ bool operator==(const S& other) const {
return this->a == other.a;
}
};
in its use, two structs can easily be created as constexpr
with an initialization list
int main() {
constexpr S s1 = {1};
constexpr S s2 = {2};
constexpr bool b = s1 == s2; // error
return 0;
}
the bool comparison can't compile because the ==
operator is not marked as constexpr
, When it is, the program compiles.
Should all comparison operators for any class that can be constexpr
also be marked as constexpr
? I don't see any reason why not, but I also haven't seen code practicing this.
I would also take it a step further and ask if something like operator*(S, S)
should be constexpr
as well, all the time.
The Thing is that comparison is not always the type that the user could use standard comparison operators.Sometimes two objects can be compared and greater than
or less Than
or equals to
can have new definitions .For example in a class that holds objects of type Coordinates Comparison can be defined in a custom way. For example :
Coordinate c1(3,5)
Coordinate c2(4,2)
We can overload the ==
operator to return True for c1==c2
whenever c1.x == c2.x
or c1.y==c2.y
or when both expressions are true.
The same goes for constexpr
type objects and structs
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