compare_compare_three_way

compare_compare_three_way (세 방향 비교 함수 객체)

std::compare_three_way는 C++20에서 도입된 함수 객체로, 두 인자를 세 방향 비교(<=>)하여 그 결과를 돌려줘요. 이 객체는 인자 타입과 반환 타입을 자동으로 추론하며, 투명한(transparent) 함수자로 동작해요. 포인터 비교 시에는 구현 정의된 엄격한 전체 순서를 사용해요.

출처: cppreference

본문

정의

헤더 에 정의됨
헤더 에 정의됨
struct compare_three_way ; (since C++20)

비교를 수행하는 함수 객체예요. 함수 호출 연산자의 매개변수 타입과 반환 타입을 추론해요.

중첩 타입

중첩 타입 정의
is_transparent 불명(unspecified)

멤버 함수

operator() 두 인자에 대한 세 방향 비교 결과를 얻어요 (공개 멤버 함수)

std::compare_three_way::operator()

template < class T , class U > constexpr auto operator ()( T && t , U && u ) const ;

표현식 std::forward(t) <=> std::forward(u)를 expr이라고 할 때:

  • expr이 포인터를 비교하는 내장 operator<=> 호출로 귀결되면, t와 u의 합성 포인터 타입(composite pointer type)을 P라고 해요:
    • 변환된 두 포인터(타입 P)를 구현 정의된 포인터 엄격한 전체 순서(strict total order)로 비교해요. t가 u보다 앞서면 std::strong_ordering::less를 반환하고, u가 t보다 앞서면 std::strong_ordering::greater를, 그 외에는 std::strong_ordering::equal을 반환해요. T에서 P로의 변환 시퀀스 또는 U에서 P로의 변환 시퀀스가 동등 보존(equality-preserving)이 아니면 동작은 정의되지 않아요.
  • 그 외의 경우:
    • expr의 결과를 반환해요. std::three_way_comparable_with<T, U>가 모델링되지 않으면 동작은 정의되지 않아요.

이 오버로드는 std::three_way_comparable_with<T, U>가 충족될 때만 오버로드 해석에 참여해요.

예제

#include <compare>
#include <iostream>

struct Rational
{
    int num;
    int den; // > 0
    
    // Although the comparison X <=> Y will work, a direct call
    // to std::compare_three_way{}(X, Y) requires the operator==
    // be defined, to satisfy the std::three_way_comparable_with.
    constexpr bool operator==(Rational const&) const = default;
};

constexpr std::weak_ordering operator<=>(Rational lhs, Rational rhs)
{
    return lhs.num * rhs.den <=> rhs.num * lhs.den;
}

void print(std::weak_ordering value)
{
    value < 0 ? std::cout << "less\n" :
    value > 0 ? std::cout << "greater\n" :
                std::cout << "equal\n";
}

int main()
{
    Rational a{6, 5};
    Rational b{8, 7};
    print(a <=> b);
    print(std::compare_three_way{}(a, b));
}

출력:

greater
greater

결함 보고서

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.

DR 적용 대상 발표된 동작 올바른 동작
LWG 3530 C++20 포인터 비교 시 문법적 검사가 완화됨 의미론적 요구사항만 완화됨

같이 보기

ranges::equal_to (C++20) x == y를 구현하는 제약된 함수 객체 (클래스) [편집]
ranges::not_equal_to (C++20) x != y를 구현하는 제약된 함수 객체 (클래스) [편집]
ranges::less (C++20) x < y를 구현하는 제약된 함수 객체 (클래스) [편집]
ranges::greater (C++20) x > y를 구현하는 제약된 함수 객체 (클래스) [편집]
ranges::less_equal (C++20) x <= y를 구현하는 제약된 함수 객체 (클래스) [편집]
ranges::greater_equal (C++20) x >= y를 구현하는 제약된 함수 객체 (클래스) [편집]

더 알아보기

cppreference