How to implement C ++ (in) equality operators for aggregate structures?

Sometimes I have structures like this -

struct aggregate1 {
  std::string name;
  std::vector<ValueT> options;
  size_t foobar;
  // ...
};

- where the (in) equality is simply defined as the (in) equality of all Member States: lhs_name == rhs_name && lhs_options == rhs_options && lhs_foobar == rhs_foobar.

What is the “best” way to implement this? (The best, as in: (Runtime-) Efficiency, maintainability, readability)

  • operator== in terms operator!=
  • operator!= in terms operator==
  • Separate implementations for ==and!=
  • As a member or as free features?

Please note that this question concerns only (in) equality ops, as a comparison ( <, <=, ...) does not have much use for such units.

+8
source share
4 answers

- - , == != , ( , ) - ( ! ).

: " operator== operator!= ?

, // ; , . , " ", , , , , , , .

+6

, , , == definition cpp. != Inline

-, , , , .

struct aggregate1 {
  bool operator==(const aggregate1& rhs) const
  {
     return (name == rhs.name)
     && (options == rhs.options)
     && (foobar == rhs.foobar);
  }
  bool operator!=(const aggregate1& rhs) const
  {
    return !operator==(rhs);
  }

  std::string name;
  std::vector<ValueT> options;
  size_t foobar;

  // ...
};
+8

IMHO, operator== ( STL , ), operator!= equals.

+1

(-: Self answer: -)

WRT:

op== op!= () .

(a-eq), (b-neq) , :

  • (a-eq) + operator==: , true
  • (a-eq) + operator!=: false
  • (b-neq) + operator==: returns false after determining the 1st sub-element of the inequality
  • (b-neq) + operator!=: Returns true after determining the 1st sub-element of the inequality

Since productivity is on average the same in any case - at least for me - it is more natural to implement op!=in terms op==, since it becomes more natural for me to realize the equality op.

-1
source

All Articles