我经常有提供简单的逐个成员比较的类:
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++ 不提供任何构造来生成运算符== https://stackoverflow.com/questions/217911/why-dont-c-compilers-define-operator-and-operator,除了我在数据成员下面添加的评论之外,是否有更好的方法来确保未来的成员成为比较的一部分?
它并不能捕获所有情况,而且令人烦恼的是它依赖于编译器和平台,但一种方法是static_assert
基于sizeof
类型:
static_assert<sizeof(*this) == <n>, "More members added?");
where <n>
is a constexpr
.
如果引入新成员,那么通常情况下,sizeof
更改,并且会导致编译时失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)