How to compare objects of POD types

Since C++11 we can use tuples for simple POD comparison (tuples use lexicographical comparison for >, <, >= and <= operators, more info on that: https://en.cppreference.com/w/cpp/utility/tuple/operator_cmp ) :

#include <iostream>
#include <tuple>

struct Point {
    int x;
    int y;
    int z;    
};


auto pointToTuple(const Point& p) {
    return std::make_tuple(p.x, p.y, p.z);
}

bool operator==(const Point& lhs, const Point& rhs ) {
    return pointToTuple(lhs) == pointToTuple(rhs);
}

bool operator<(const Point& lhs, const Point& rhs ) {
    return pointToTuple(lhs) < pointToTuple(rhs);
}

int main()
{

    Point a{1, 2, 3};
    Point b{1, 2, 3};
    Point c{2, 2, 2};

    std::cout << (pointToTuple(a) == pointToTuple(b) ? "true" : "false") << "\n"; //true
    std::cout << (pointToTuple(a) == pointToTuple(c) ? "true" : "false") << "\n"; //false

    std::cout << (a == b ? "true" : "false") << "\n"; //true
    std::cout << (a == c ? "true" : "false") << "\n"; //false

    std::cout << (a < b ? "true" : "false") << "\n"; //false
    std::cout << (a < c ? "true" : "false") << "\n"; //true

}

C++20 should bring us default comparisons (https://en.cppreference.com/w/cpp/language/default_comparisons). So if class defines operator<=> as defaulted, compiler will automatically generate ==, !=, <, <=, > and >= operators and code for them:

struct Point {
    int x;
    int y;
    int z;    

    auto operator<=>(const Point&) const = default;
};

The first one is not working because of padding in the struct. The padding is having different bit patterns for both objects.

If you use memset to set all the bits in the object before using it, then it will work:

A a1;
std::memset(&a1, 0, sizeof(A));
a1.a = 5;a1.b = true;

A a2;
std::memset(&a2, 0, sizeof(A));
a2.a = 5;a2.b = true;

Online demos:

  • http://www.ideone.com/mVmsn (Original code written by you)
  • http://www.ideone.com/Q13QO (My modification)

By the way, you can write operator<, operator== etc, for PODs also.

Tags:

C++