我经常有一些类提供简单的逐个成员比较:
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));
}
Run Code Online (Sandbox Code Playgroud)
鉴于此时C++没有提供任何构造来生成运算符==,是否有更好的方法来确保未来成员成为比较的一部分,而不是我在数据成员下面添加的注释?
它没有捕获每一个案例,并且令人讨厌它的编译器和平台依赖,但一种方法是static_assert
基于sizeof
类型:
static_assert<sizeof(*this) == <n>, "More members added?");
Run Code Online (Sandbox Code Playgroud)
这里<n>
是一个constexpr
.
如果引入了新成员,那么通常会sizeof
发生更改,并且会导致编译时失败.
归档时间: |
|
查看次数: |
268 次 |
最近记录: |