개념

  • C++20에서 도입된 비교 연산자 operator<=>

  • 세 가지 결과를 한 번에 반환: 작음 / 같음 / 큼

  • 예: auto result = a <=> b;

    • result < 0 → a < b
    • result == 0 → a == b
    • result > 0 → a > b

반환 타입

간략하게 아래와 같은데 다른 글에서 설명

  • std::strong_ordering: 완전한 정렬 + 일관된 같음
  • std::weak_ordering: 같음은 구분되나 정렬은 보장
  • std::partial_ordering: NaN 등 비교 불가능한 경우 포함

Rewrite Expression

  • 비교 연산자 (==, !=, <, <=, >, >=)는 operator<=>로 재작성 가능
  • 예: a < b(a <=> b) < 0으로 rewrite 됨

예제

  #include <compare>

class Int32 {
    int value;
public:
    explicit Int32(int v = 0) : value(v) {}

    auto operator<=>(const Int32& other) const {
        return value <=> other.value;
    }
    bool operator==(const Int32& other) const {
        return value == other.value;
    }

    auto operator<=>(int other) const {
        return value <=> other;
    }
    bool operator==(int other) const {
        return value == other;
    }
};

int main() {
    Int32 n1{10}, n2{20};
    bool b1 = n1 == n2;  // n1.operator==(n2)
    bool b2 = n1 != n2;  // !(n1 == n2)
    bool b3 = n1 < n2;   // (n1 <=> n2) < 0
    bool b4 = n1 > n2;   // (n1 <=> n2) > 0
    bool b5 = n1 < 10;   // (n1 <=> 10) < 0
    bool b6 = 10 < n1;   // (10 <=> n1) < 0 → (n1 <=> 10) > 0
}
  

사용자 정의 타입에서의 사용

자동 구현 (C++20)

  struct Point3D {
    int x, y, z;
    auto operator<=>(const Point3D&) const = default;
};
  
  • 위와 같이 하면 ==, <=> 모두 자동 생성
  • 비교는 lexicographical 방식으로 수행됨

==도 명시적으로 정의하면 좋다

  • ==는 최적화 여지가 많다.
  • 예: 문자열 비교 시 size 비교 → 빠른 탈출
  • operator==을 직접 정의하면 최적화 가능

요약

항목설명
도입 버전C++20
연산자<=> (우주선 연산자)
반환 타입std::strong_ordering, weak_ordering, partial_ordering
rewrite 적용 대상<, <=, >, >=, != 등 비교 연산
default 지원= default 지정 시 자동 비교 구현
== 직접 구현 이유성능 최적화를 위해 수동 구현 가능