Mar*_* Ba 10 c++ equality operator-overloading operators
有时候我有这样的结构 -
struct aggregate1 {
std::string name;
std::vector<ValueT> options;
size_t foobar;
// ...
};
Run Code Online (Sandbox Code Playgroud)
- 其中(in)等式简单地定义为(in)所有成员的相等:lhs_name == rhs_name && lhs_options == rhs_options && lhs_foobar == rhs_foobar.
实现这一目标的"最佳"方式是什么?(最佳:(运行时)效率,可维护性,可读性)
operator== 就......而言 operator!=operator!= 就......而言 operator====和!=请注意,这个问题只是关于(不)平等OPS,作为比较(<,<=,...)并没有什么太大的意义了这样的聚集.
我会这样做,但可能会将operator == definition移动到cpp文件.离开operator!=是内联的
请记住比较最有可能首先不同的成员变量,以便其余变量短路并且性能更好.
struct aggregate1 {
bool operator==(const aggregate1& rhs) const
{
return (name == rhs.name)
&& (options == rhs.options)
&& (foobar == rhs.foobar);
}
bool operator!=(const aggregate1& rhs) const
{
return !operator==(rhs);
}
std::string name;
std::vector<ValueT> options;
size_t foobar;
// ...
};
Run Code Online (Sandbox Code Playgroud)
会员或免费功能是一个品味的问题,并编写单独的实现,==并!=在我看来很无聊,容易出错(你可能会忘记两个运营商中的一个成员,并且需要时间注意),而无需添加任何内容效率条款(称其他运营商和申请!费用可忽略不计).
决定仅限于"是更好地执行operator==来讲operator!=还是相反?
在我看来,在可维护性/可读性/效率方面它是一样的; 我只建议以相同的方式在任何地方以一致的方式进行.你想要更喜欢使用一个或另一个作为"基本运算符"的唯一情况是当你知道,在你的结构中包含的类型中,该运算符比它的否定更快,但我不知道何时会发生这种情况.
小智 3
在 C++20 中,实现相等和不等运算符可以像声明一样operator==简单default:
struct S {
int x;
// ...
// As member function
bool operator==(S const &) const = default;
// As non-member function (hidden friend)
// friend bool operator==(S const &, S const &) = default;
};
Run Code Online (Sandbox Code Playgroud)
如果仅operator==提供,a!=b则被解释为!(a==b)根据重载决策,因此无需为 提供显式重载operator!=。
我认为默认operator==为隐藏好友更好,因为它适用于引用包装的对象:
S s;
auto rs{std::ref(s)};
rs==rs; // OK for hidden friend; ill-formed if declared as member function
Run Code Online (Sandbox Code Playgroud)
在此示例中,operator==未为 定义std::reference_wrapper<S>,但参数相关查找 (ADL) 可以选择操作数隐式转换为 的隐藏友元S const &。但请注意,只有将定义为自由函数::operator==(rs,rs)时,这才有效,因为限定名称不会触发 ADL。operator==