rel_ops_operator_cmp

rel_ops_operator_cmp (관계 연산자 함수)

이 페이지는 <utility> 헤더의 std::rel_ops 네임스페이스에 정의된 비교 연산자 함수 템플릿들을 설명해요. 사용자 정의 타입에 대해 operator==operator<만 정의되어 있으면, 나머지 비교 연산자(!=, >, <=, >=)를 자동으로 제공받을 수 있어요. C++20부터는 operator<=>가 도입되면서 이 함수들은 폐기되었어요.

출처: cppreference

본문

std::rel_ops 네임스페이스의 이 함수들은 사용자 정의 operator==operator<를 기반으로 나머지 비교 연산자들의 일반적인 의미를 구현해요. 이 함수들을 사용하려면 using namespace std::rel_ops;를 선언하면 돼요.

함수 목록

<utility> 헤더에 정의됨
template < class T > bool operator != ( const T & lhs , const T & rhs ); (1) (C++20에서 폐기됨)
template < class T > bool operator > ( const T & lhs , const T & rhs ); (2) (C++20에서 폐기됨)
template < class T > bool operator <= ( const T & lhs , const T & rhs ); (3) (C++20에서 폐기됨)
template < class T > bool operator >= ( const T & lhs , const T & rhs ); (4) (C++20에서 폐기됨)

타입 T에 대해 사용자 정의 operator==operator<가 주어지면, 이 함수들이 다른 비교 연산자들의 일반적인 의미를 구현해요.

매개변수

lhs - 왼쪽 인자
rhs - 오른쪽 인자

반환값

각 연산자는 다음과 같은 값을 반환해요:

  • (1) operator!=: !(lhs == rhs)
  • (2) operator>: rhs < lhs
  • (3) operator<=: !(rhs < lhs)
  • (4) operator>=: !(lhs < rhs)

가능한 구현

(1) operator!=
namespace rel_ops { template < class T > bool operator != ( const T & lhs , const T & rhs ) { return ! ( lhs == rhs ); } }
(2) operator>
namespace rel_ops { template < class T > bool operator > ( const T & lhs , const T & rhs ) { return rhs < lhs ; } }
(3) operator<=
namespace rel_ops { template < class T > bool operator <= ( const T & lhs , const T & rhs ) { return ! ( rhs < lhs ); } }
(4) operator>=
namespace rel_ops { template < class T > bool operator >= ( const T & lhs , const T & rhs ) { return ! ( lhs < rhs ); } }

참고 사항

Boost.operators는 std::rel_ops보다 더 다양한 용도를 제공하는 대안이에요.

C++20부터 std::rel_opsoperator<=>를 위해 폐기되었어요.

예제

#include <iostream>
#include <utility>

struct Foo
{
    int n;
};

bool operator==(const Foo& lhs, const Foo& rhs)
{
    return lhs.n == rhs.n;
}

bool operator<(const Foo& lhs, const Foo& rhs)
{
    return lhs.n < rhs.n;
}

int main()
{
    Foo f1 = {1};
    Foo f2 = {2};
    using namespace std::rel_ops;

    std::cout << std::boolalpha
              << "{1} != {2} : " << (f1 != f2) << '\n'
              << "{1} >  {2} : " << (f1 >  f2) << '\n'
              << "{1} <= {2} : " << (f1 <= f2) << '\n'
              << "{1} >= {2} : " << (f1 >= f2) << '\n';
}

출력:

{1} != {2} : true
{1} >  {2} : false
{1} <= {2} : true
{1} >= {2} : false

더 알아보기 (Learn more)

cppreference