我有一个需要比较操作的旧类,因为我们想按照成员的顺序按其成员对其进行排序。所以旧的类定义很简单
struct old_class { std::string a; std::optional<std::string> b; std::optional<std::string> c; friend auto operator<=>(const old_class&, const old_class&) = default; };
然而,现在添加了另一个数据字段/成员,但不应在比较操作中使用,因此我必须提供自己的 operator<=> ,但我很困惑如何编写一个与旧类中行为相同的类:
operator<=>
struct new_class { std::string a; std::optional<std::string> b; std::optional<std::string> c; int new_data_field_not_to_be_compared; friend auto operator<=>(const new_class& lhs, const new_class& rhs) -> std::strong_ordering { return (std::tie(lhs.a,rhs.a) <=> std::tie(lhs.b,rhs.b)) <=> std::tie(lhs.c,rhs.c); } };
我该如何更正 new_class::operator<=> ?
new_class::operator<=>
MRE on coliru
std::tie(lhs.a,rhs.a) <=> std::tie(lhs.b,rhs.b)
这将比较两个(强制)字符串 a 带有两个可选字符串 b .成员 lhs 与不同的成员进行比较 lhs ,同上 rhs 成员。
a
b
lhs
rhs
保持与之前相同的行为 = default 您需要比较以下成员 lhs 与相应的成员 rhs .
= default
std::tie(lhs.a, lhs.b, lhs.c) <=> std::tie(rhs.a, rhs.b, rhs.c)