You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正新增非比较成员后的C++三路比较运算符operator<=>

修正new_class的operator<=>实现

旧类默认的operator<=>会按照成员声明的顺序(a → b → c)依次进行比较:仅当前一个成员相等时,才会继续比较下一个成员。要让新类的比较逻辑和旧类完全一致,你需要将需要参与比较的成员按顺序打包进std::tie,再通过元组的三路比较实现逻辑。

当前的实现逻辑错误,正确的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, lhs.b, lhs.c) <=> std::tie(rhs.a, rhs.b, rhs.c);
    }
};

错误原因说明

你之前的代码错误地将lhs.a与rhs.a、lhs.b与rhs.b分别打包后比较,再将结果与c的打包结果嵌套比较,这完全不符合默认比较的"顺序逐个比较"规则。而std::tie(lhs.a, lhs.b, lhs.c)会生成包含三个成员的元组,元组的三路比较会严格按照元素顺序依次对比,和旧类默认生成的operator<=>行为完全一致,同时自动忽略不需要参与比较的new_data_field_not_to_be_compared成员。

内容的提问来源于stack exchange,提问作者Superlokkus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 14:45:59