C++ equal(==) overload, Shortcut or best way comparing all attributes

There is no shortcut. You will have to list everything.

Some sources of error can be reduced by introducing a member function named tied() like:

struct Foo {
    A a;
    B b;
    C c;
    ...

private:
    auto tied() const { return std::tie(a, b, c, ...); }
};

So that your operator== can just use that:

bool operator==(Foo const& rhs) const { return tied() == rhs.tied(); }

This lets you only list all your members once. But that’s about it. You still have to actually list them (so you can still forget one).


There is a proposal (P0221R0) to create a default operator==, but I don’t know if it will get accepted.


The above proposal was rejected in favor of a different direction regarding comparisons. C++20 will allow you to write:

struct Foo {
    A a;
    B b;
    C c;

    // this just does memberwise == on each of the members
    // in declaration order (including base classes)
    bool operator==(Foo const&) const = default;
};

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)