如何避免在C ++中的operator ==实现中出错? [英] How to avoid mistakes in operator== implementations in C++?
问题描述
我经常有一些提供简单的逐成员比较的类:
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?
推荐答案
它不能满足所有情况,而且令人讨厌的是它依赖于编译器和平台,但是一种方法是根据类型的sizeof
来static_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屋!