简体   繁体   中英

Is there a way to have a compile time check, that all members of a class are compared within operator==

I was wondering if there is a way in C++ to have a compile time check, that verifies that all member variables of a class are compared by operator== ? And if there is it would also be useful to have a way to explicitly ignore this constaint on some members.

This is useful for my use case in which there is a data structure that is changing over time in our development process, and it happened multiple times already that adjusting the existing operator== was forgotten. This is a silent error which results in a, let's call it "false positive behaviour", which is hard to find.

Any information is appreciated. Maybe alternative ways to solve the problem, or an explanation to why this compile time check might not be possible.

EDIT: Sadly I am using C++17 and there is no way to update to C++20 in the near future.

With C++20, assuming all your class members are themselves == comparable, you can simply provide a defaulted definition:

class C {
    // members
public:
    bool operator==(C const&) const = default;
};

When you'll update your class, the defaulted operator will pick up on the new members automictically.


As far as ignoring members in the comparison. That's always going to be a bit involved, as defaulted operations can sometimes be. One approach would be to use a nested class

class C {
    // members
    struct NoEqCompare {
       mutable std::mutex mut; // A member you may want to omit.
       bool operator==(NoEqCompare const&) const { return true; }
    } eqIgnore;
public:
    bool operator==(C const&) const = default;
};

Unlike the old trick of std::tie -ing the members you want on a per-operator basis, this has the potential to be a bit more intractable if we need to add more operators into the mix, and then mix and match the members. Weigh your options.

The fundamental problem here is that you cannot iterate over class members.

The quick solution is to pack all the members which play a part in operator== into a std::tuple .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM