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

标签 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== , 除了我在数据成员下方添加的评论之外,是否有更好的方法来确保 future 的成员成为比较的一部分?

最佳答案

它并不能捕捉到所有情况,令人恼火的是它依赖于编译器和平台,但一种方法是 static_assert基于 sizeof类型:

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

哪里<n>constexpr .

如果引入新成员,通常情况下,sizeof更改,您将导致编译时失败。

关于c++ - 如何避免 C++ 中 operator== 实现的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49127705/

相关文章:

c - 为什么 < 比 != 快得多?

c++ - 两个 union 之间的循环转换运算符

java - InterShop 日期比较条件不起作用

c++ - 使用 MoveWindow 或 SetWindowPos 时,编辑控件/组合框的窗口大小未正确调整

c++ - 将二维数组复制到 C++ 中未知大小的其他二维数组

c++ - 什么时候需要在 Ruby C 扩展中声明 volatile VALUE?

mysql - 使用 OR 和 NAND 选择查询

c++ - 如何阻止函数在 MS VS C++ 中导出?

C++ 分析/优化 : How to get better profiling granularity in an optimized function

c# - 为什么 ? : operator does not work with nullable<int> assignation?