三向比较运算符 <=>(Spaceship Operator) ​

什么是三向比较运算符 ​

C++20 引入了三向比较运算符 <=>,因为它的形状像一艘飞船,也被叫做"太空船运算符"(Spaceship Operator)。它的作用是用一次比较就能确定两个值之间的完整关系:小于、等于还是大于。

在 C++20 之前,要让一个类支持完整的比较操作,你需要手动定义 6 个比较运算符:==、!=、<、<=、>、>=。如果有 3 种不同类型之间的比较,就需要 18 个运算符——大量无聊的样板代码。

有了 <=>,你只需要定义一个运算符(甚至用 = default 让编译器自动生成),编译器就会自动合成全部 6 个比较运算符。

头文件 ​

cpp
#include <compare>  // 比较类别类型:strong_ordering, weak_ordering, partial_ordering

三种比较类别 ​

<=> 运算符的返回类型不是 bool,而是以下三种比较类别之一:

比较类别含义典型类型可能的值
std::strong_ordering全序,相等的值完全不可区分int、char、enum、指针less、equal、greater
std::weak_ordering全序,但相等的值可能有区别大小写不敏感的字符串比较less、equivalent、greater
std::partial_ordering偏序,某些值之间不可比较float、double(因为 NaN)less、equivalent、greater、unordered

关键区别:

  • strong_ordering:a == b 意味着 a 和 b 在任何方面都不可区分(可以互相替换)
  • weak_ordering:a == b 意味着 a 和 b 在排序意义上等价,但可能有其他差异
  • partial_ordering:某些值之间可能无法比较(比如 NaN 和任何数比较都返回 unordered)

基本示例 ​

cpp
#include <iostream>
#include <compare>
#include <string>
#include <set>
#include <vector>
#include <algorithm>

// ============================
// 示例1:默认三向比较(最简单的用法)
// ============================

struct Point {
    int x;
    int y;

    // 编译器自动按成员声明顺序逐一比较
    // 先比较 x,x 相等再比较 y
    auto operator<=>(const Point&) const = default;
};

void default_spaceship_demo() {
    Point p1{1, 2}, p2{1, 3}, p3{1, 2};

    // 一个 operator<=> = default 就生成了全部 6 个运算符
    std::cout << std::boolalpha;
    std::cout << "p1 == p3: " << (p1 == p3) << std::endl;  // true
    std::cout << "p1 != p2: " << (p1 != p2) << std::endl;  // true
    std::cout << "p1 < p2:  " << (p1 < p2) << std::endl;   // true
    std::cout << "p1 <= p2: " << (p1 <= p2) << std::endl;  // true
    std::cout << "p2 > p1:  " << (p2 > p1) << std::endl;   // true
    std::cout << "p2 >= p1: " << (p2 >= p1) << std::endl;  // true

    // 可以直接用在 set、map、sort 中
    std::set<Point> points{p1, p2, p3};
    std::cout << "set 中的点数: " << points.size() << std::endl;  // 2(p1 和 p3 相等)
}

// ============================
// 示例2:自定义三向比较
// ============================

struct Version {
    int major;
    int minor;
    int patch;

    // 自定义比较逻辑:按 major -> minor -> patch 顺序比较
    std::strong_ordering operator<=>(const Version& other) const {
        // 先比较 major
        if (auto cmp = major <=> other.major; cmp != 0) return cmp;
        // major 相等,比较 minor
        if (auto cmp = minor <=> other.minor; cmp != 0) return cmp;
        // minor 也相等,比较 patch
        return patch <=> other.patch;
    }

    // 注意:自定义 <=> 时,== 不会自动生成,需要单独声明
    bool operator==(const Version& other) const = default;
};

void custom_spaceship_demo() {
    Version v1{1, 2, 0};
    Version v2{1, 3, 0};
    Version v3{2, 0, 0};

    std::cout << "v1 < v2:  " << (v1 < v2) << std::endl;   // true
    std::cout << "v3 > v2:  " << (v3 > v2) << std::endl;   // true
    std::cout << "v1 == v1: " << (v1 == v1) << std::endl;   // true

    // 使用 <=> 的结果
    auto result = v1 <=> v2;
    if (result < 0) std::cout << "v1 < v2" << std::endl;
    else if (result > 0) std::cout << "v1 > v2" << std::endl;
    else std::cout << "v1 == v2" << std::endl;
}

// ============================
// 示例3:浮点数与 partial_ordering
// ============================

struct Measurement {
    double value;

    // double 的 <=> 返回 partial_ordering(因为 NaN)
    auto operator<=>(const Measurement&) const = default;
};

void partial_ordering_demo() {
    Measurement m1{3.14}, m2{2.71};
    Measurement nan_m{std::numeric_limits<double>::quiet_NaN()};

    std::cout << "3.14 > 2.71: " << (m1 > m2) << std::endl;       // true
    std::cout << "NaN == NaN:  " << (nan_m == nan_m) << std::endl;  // false
    std::cout << "NaN < 3.14:  " << (nan_m < m1) << std::endl;     // false
    std::cout << "NaN > 3.14:  " << (nan_m > m1) << std::endl;     // false
    // NaN 和任何值都不可比较——所有比较都返回 false
}

// ============================
// 示例4:混合类型比较
// ============================

struct Celsius {
    double temp;

    // 和 double 的比较
    auto operator<=>(double other) const {
        return temp <=> other;
    }

    bool operator==(double other) const {
        return temp == other;
    }
};

void mixed_comparison_demo() {
    Celsius c{100.0};

    // 编译器会自动翻转参数顺序
    std::cout << "c > 50.0:   " << (c > 50.0) << std::endl;    // true
    std::cout << "50.0 < c:   " << (50.0 < c) << std::endl;    // true(自动翻转)
    std::cout << "c == 100.0: " << (c == 100.0) << std::endl;  // true
}

// ============================
// 示例5:排序中使用
// ============================

struct Student {
    std::string name;
    int score;

    // 按分数降序,分数相同按名字升序
    std::strong_ordering operator<=>(const Student& other) const {
        // 先比分数(注意是 other.score <=> score,实现降序)
        if (auto cmp = other.score <=> score; cmp != 0) return cmp;
        // 分数相同比名字(升序)
        return name <=> other.name;
    }

    bool operator==(const Student& other) const = default;
};

void sorting_demo() {
    std::vector<Student> students{
        {"Alice", 90},
        {"Bob", 85},
        {"Charlie", 90},
        {"David", 95}
    };

    std::sort(students.begin(), students.end());

    std::cout << "排序结果:" << std::endl;
    for (const auto& s : students) {
        std::cout << "  " << s.name << ": " << s.score << std::endl;
    }
    // David: 95, Alice: 90, Charlie: 90, Bob: 85
}

int main() {
    std::cout << "=== 默认 <=> ===" << std::endl;
    default_spaceship_demo();

    std::cout << "\n=== 自定义 <=> ===" << std::endl;
    custom_spaceship_demo();

    std::cout << "\n=== partial_ordering ===" << std::endl;
    partial_ordering_demo();

    std::cout << "\n=== 混合类型比较 ===" << std::endl;
    mixed_comparison_demo();

    std::cout << "\n=== 排序 ===" << std::endl;
    sorting_demo();

    return 0;
}

编译器自动生成运算符的规则 ​

当你写 auto operator<=>(const T&) const = default; 时:

你写的编译器自动生成的
operator<=><、>、<=、>=
operator==(由 default <=> 隐式生成)!=

当你自定义 operator<=> 时(非 = default):

你写的编译器自动生成的需要你手动写的
自定义 operator<=><、>、<=、>=operator==(不会自动生成)

这是因为对于某些类型,== 的实现可以比"调用 <=> 然后检查结果是否为 0"更高效(比如 std::string 可以先比较长度来快速排除不相等的情况)。

适用场景 ​

  • 值类型(Value Types):坐标点、版本号、日期、RGB 颜色等需要完整比较支持的类型
  • 需要排序的类型:放入 std::set/std::map 或用 std::sort 排序的类型
  • 减少样板代码:用一行 = default 替代 6 个手写运算符
  • 混合类型比较:类与内置类型之间的比较

常见问题 ​

为什么自定义 <=> 时不自动生成 ==?

因为 == 的最优实现经常和 <=> 不同。比如比较两个字符串是否相等,最快的方法是先比较长度——长度不同就直接不相等。而 <=> 需要逐字符比较。如果 == 由 <=> 推导(检查结果是否为 0),就会失去这种优化机会。

什么时候用 strong_ordering,什么时候用 weak_ordering?

如果两个对象"相等"意味着它们在所有可观察的方面都一样(可以互相替换),用 strong_ordering。如果"等价"只意味着在排序中位置相同但可能有其他差异(如大小写不敏感的字符串比较),用 weak_ordering。

包含 float/double 成员的结构体,默认 <=> 返回什么?

partial_ordering,因为 float/double 有 NaN 值。如果你确定你的类型不会包含 NaN,可以自定义 <=> 返回 strong_ordering 或 weak_ordering。

注意事项 ​

  • = default 的 <=> 按成员声明顺序逐一比较,先基类后成员
  • 自定义 <=> 时必须单独声明 operator==(可以用 = default)
  • <=> 的返回值不能直接用作 bool,需要和 0 比较(result < 0、result == 0、result > 0)
  • 包含不可比较成员(如 std::function)的类不能使用 = default
  • 编译器会自动翻转操作数顺序:如果定义了 a <=> b,b < a 也能工作
  • <=> 是 constexpr 和 noexcept 的(当默认生成且所有成员的 <=> 也是时)

编译器支持情况 ​

编译器最低支持版本
GCC10.0
Clang10.0
MSVC19.26 (VS 2019 16.6)

总结 ​

三向比较运算符 <=> 是 C++20 对比较操作的一次彻底改革。它用一个运算符替代了之前需要手写的 6 个比较运算符,大幅减少了样板代码。对于简单的值类型,一行 auto operator<=>(const T&) const = default; 就够了——编译器会按成员声明顺序逐一比较,自动推导出正确的比较类别(strong_ordering、weak_ordering 或 partial_ordering),并自动生成全部 6 个比较运算符。对于需要自定义比较逻辑的类型,手动实现 <=> 后编译器会自动生成 <、>、<=、>=,但需要单独声明 operator==。