代码之家  ›  专栏  ›  技术社区  ›  Superlokkus

将宇宙飞船(即三向比较算子)与特定成员组合在一起

  •  1
  • Superlokkus  · 技术社区  · 6 月前

    我有一个需要比较操作的旧类,因为我们想按照成员的顺序按其成员对其进行排序。所以旧的类定义很简单

    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<=> ,但我很困惑如何编写一个与旧类中行为相同的类:

    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<=> ?

    MRE on coliru

    1 回复  |  直到 6 月前
        1
  •  3
  •   Caleth    6 月前

    std::tie(lhs.a,rhs.a) <=> std::tie(lhs.b,rhs.b)

    这将比较两个(强制)字符串 a 带有两个可选字符串 b .成员 lhs 与不同的成员进行比较 lhs ,同上 rhs 成员。

    保持与之前相同的行为 = default 您需要比较以下成员 lhs 与相应的成员 rhs .

    std::tie(lhs.a, lhs.b, lhs.c) <=> std::tie(rhs.a, rhs.b, rhs.c)
    
    推荐文章