天天看點

C++20之飛船比較符<=> 強序,弱序,偏序

  1. std::tuple<>預設按順序比較
  2. std::tie能把值引用打包
  3. C++20 <=>能按成員變量聲明順序比較
#include <iostream>
#include "common/log.h"
#include <limits>
#include <vector>
#include <span>
#include <array>
#include <type_traits>
#include <cmath>
#include <memory>
#include <variant>
using namespace AdsonLib;

struct Point1{
    int x;
    int y;
    friend bool operator==(const Point1 &a, const Point1 &b);
    friend bool operator<(const Point1 &a, const Point1 &b);
};

bool operator==(const Point1 &a, const Point1 &b) {
    return std::tie(a.x, a.y) == std::tie(b.x, b.y);
}
bool operator<(const Point1 &a, const Point1 &b) {
    return std::tie(a.x, a.y) < std::tie(b.x, b.y);
}

struct Point2{
    Point2(int a, int b):x(a), y(b){}
    virtual ~Point2(){}
    int x;
    int y;
    //預設比較,按成員定義順序. 可以有虛函數
    friend auto operator<=>(const Point2 &a, const Point2 &b) = default; 
};


struct Point3{
    int x;
    int y;
    //預設比較,按成員定義順序. 可以有虛函數
    friend auto operator<=>(const Point3 &a, const Point3 &b); 
};
auto operator<=>(const Point3 &a, const Point3 &b) {
    auto v1 = a.x * a.y;
    auto v2 = b.x * b.y;
    return v1 - v2;
}
//偏序(partial_ordering):不是任意兩個可比較大小
//弱序(weak_ordering):任意兩個可比較大小,但是相等定義為不大于也不小于
//強序(strong_ordering):任意兩個可比較大小,也定義了相等比較
int main(int argc, char *argv[]) {
    std::tuple t1(0,3);
    std::tuple t2(0,2);
    auto t3 = std::tuple(4,5);
    auto b = (t1 <=> t3);
    Point2 p20{0,1};
    Point2 p21{0,2};
    LOG(INFO) << "cmp: " << (t1 < t2) << " <=> " << (p20 < p21);

    Point3 p30{4,1};
    Point3 p31{1,2};
    LOG(INFO) << (p30 > p31) << " <=> " << (p30 < p31);
}