How to avoid errors in implementations of operator == in C ++?

I often have classes that provide simple element-by-element matching:

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 for generating the == operator , is there a better way to ensure that future participants become part of the comparison, except for the comment I added below the data elements?

+4
source share
2 answers

It does not catch every case and annoys its compiler and is platform dependent, but one way is static_assertbased on the sizeoftype:

static_assert<sizeof(*this) == <n>, "More members added?");

where <n>- constexpr.

If new members are introduced, it most often sizeofchanges, and you cause a compile-time failure.

+8

, , std::tuple operator== . , . - :

#include <tuple>

class ApplicationSettings
{
public:
   bool operator==(const ApplicationSettings& other) const;
   bool operator!=(const ApplicationSettings& other) const;

private:

   enum m {
     ApplicationSkin, 
     IntervalForUpdateChecks,
     bDockSelectionWidget
   };

   std::tuple<
     SkinType,
     UpdateCheckInterval,
     bool
   > m_Data;
};

:

bool ApplicationSettings::operator==(const ApplicationSettings& other) const {
  m_Data == other.m_Data;
}

, , - std::get<m::ApplicationSkin>(m_Data). .

+4

Source: https://habr.com/ru/post/1694517/


All Articles