I often have classes which provide simple member-by-member comparison:
class ApplicationSettings
{
public:
   bool operator==(const ApplicationSettings& other) const;
   bool operator!=(const ApplicationSettings& other) const;
private:
   SkinType m_ApplicationSkin;
   UpdateCheckInterval m_IntervalForUpdateChecks;
   bool m_bDockSelectionWidget;
   // Add future members to operator==
};
bool ApplicationSettings::operator==(const ApplicationSettings& other) const
{
   if (m_ApplicationSkin != other.m_ApplicationSkin)
   {
      return false;
   }
   if (m_IntervalForUpdateChecks != other.m_IntervalForUpdateChecks)
   {
      return false;
   }
   if (m_bDockSelectionWidget != other.m_bDockSelectionWidget)
   {
      return false;
   }
   return true;
}
bool ApplicationSettings::operator!=(const ApplicationSettings& other) const;
{
   return ( ! operator==(other));
}
Given that C++ at this time does not provide any construct to generate an operator==, is there a better way to ensure future members become part of the comparison, other than the comment I added below the data members?
It doesn't catch every case, and annoyingly it's compiler and platform dependent, but one way is to static_assert based on the sizeof of the type:
static_assert<sizeof(*this) == <n>, "More members added?");
where <n> is a constexpr.
If new members are introduced then, more often than not, sizeof changes, and you'll induce a compile time failure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With