【发布时间】:2018-08-14 03:01:43
【问题描述】:
我经常有提供简单的逐个成员比较的类:
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==,除了我在数据成员下方添加的评论之外,有没有更好的方法来确保未来的成员成为比较的一部分?
【问题讨论】:
-
未来的 C++ 版本可能会在这方面提供一些帮助。请参阅CppCon2017 Herb Sutter on "Meta: Thoughts on generative C++" 谈话。但是今天我看不到自动检查或生成的方法
-
@nwp - 您仍然需要将新成员添加到对
tie的调用中。 -
您还可以编写一个函数,为您提供一个
constexpr指向成员的指针元组,因此您不需要复制成员列表。 SO上有一个问题表明了这一点,但我找不到。它还提到了magic get。 -
我提到的成员指针元组的This is an example。