Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should all comparison operators be constexpr for a potentially constexpr object

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.

like image 782
Ryan Haining Avatar asked Jan 20 '14 20:01

Ryan Haining


1 Answers

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

like image 50
fer y Avatar answered Sep 17 '22 17:09

fer y