如何避免C ++中operator ==实现中的错误?

时间:2018-03-06 09:43:19

标签: c++ operators

我经常有一些类提供简单的逐个成员比较:

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==,除了我在数据成员下面添加的评论之外,还有更好的方法可以确保未来的成员参与比较吗?

2 个答案:

答案 0 :(得分:8)

它并不能捕捉每一个案例,并且令人讨厌它的编译器和平台依赖,但一种方法是static_assert基于类型的sizeof

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

其中<n>constexpr

如果引入了新成员,那么sizeof经常会发生变化,并且会导致编译时失败。

答案 1 :(得分:4)

仅关注技术方面,您可以利用标准库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)访问其他成员。这可能会引起一些人的注意。