Define generic comparison operator

Viewed 2997

I came up with the idea to define a generic comparison operator which would work with any type, for the fun of it.

#include <cstring>
#include <iostream>

class A
{
    public:
        A(int id) : id(id) {}

    private:
        int id;
};

template <class T>
inline bool operator==(const T& a, const T& b)
{
    return memcmp(&a, &b, sizeof(a)) == 0; // implementation is unimportant (can fail because of padding)
}

int main()
{
    std::cout << (A(10) == A(10)) << std::endl; // 1
    std::cout << (A(10) == A(15)) << std::endl; // 0
}

I think this could be useful to get around the lack of default comparison operator in c++.

Is this a terrible idea? I wonder if doing this could break anything in some circumstances?

4 Answers
Related