我经常有提供简单的逐个成员比较的类:
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/