I was working on some code recently and decided to work on my operator overloading in c++, because I've never really implemented it before. So I overloaded the comparison operators for my matrix class using a compare function that returned 0 if LHS was less than RHS, 1 if LHS was greater than RHS and 2 if they were equal. Then I exploited the properties of logical not in c++ on integers, to get all of my compares in one line:
inline bool Matrix::operator<(Matrix &RHS){
return ! (compare(*this,RHS));
}
inline bool Matrix::operator>(Matrix &RHS){
return ! (compare((*this),RHS)-1);
}
inline bool Matrix::operator>=(Matrix &RHS){
return compare((*this),RHS);
}
inline bool Matrix::operator<=(Matrix &RHS){
return compare((*this),RHS)-1;
}
inline bool Matrix::operator!=(Matrix &RHS){
return compare((*this),RHS)-2;
}
inline bool Matrix::operator==(Matrix &RHS){
return !(compare((*this),RHS)-2);
}
Obviously I should be passing RHS as a const, I'm just probably not going to use this matrix class again and I didn't feel like writing another function that wasn't a reference to get the array index values solely for the comparator operation.
As per suggestion here is the code if Compare returns -1 for less, 0 for equal and 1 for positive.
inline bool Matrix::operator<(Matrix &RHS){
return ! (compare(*this,RHS)+1);
}
inline bool Matrix::operator>(Matrix &RHS){
return ! (compare((*this),RHS)-1);
}
inline bool Matrix::operator>=(Matrix &RHS){
return compare((*this),RHS)+1;
}
inline bool Matrix::operator<=(Matrix &RHS){
return compare((*this),RHS)-1;
}
inline bool Matrix::operator!=(Matrix &RHS){
return compare((*this),RHS);
}
inline bool Matrix::operator==(Matrix &RHS){
return !(compare((*this),RHS));
}
I don't know that this really increases the readability though.