如何避免在C ++中的operator ==实现中出错? [英] How to avoid mistakes in operator== implementations in C++?

查看:103
本文介绍了如何避免在C ++中的operator ==实现中出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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));
}

鉴于C ++目前不提供任何生成的构造操作符== ,除了我在数据成员下方添加的注释之外,还有更好的方法来确保将来的成员成为比较的一部分吗?

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?

推荐答案

它不能满足所有情况,而且令人讨厌的是它依赖于编译器和平台,但是一种方法是根据类型的sizeofstatic_assert :

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?");

其中<n>constexpr.

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

If new members are introduced then, more often than not, sizeof changes, and you'll induce a compile time failure.

这篇关于如何避免在C ++中的operator ==实现中出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆