C++/STL

[C++20] <=> 삼항 연산자(우주선 연산자)

sseram 2023. 12. 3. 21:30
반응형

https://en.cppreference.com/w/cpp/utility/compare/three_way_comparable

 

std::three_way_comparable, std::three_way_comparable_with - cppreference.com

template< class T, class Cat = std::partial_ordering > concept three_way_comparable =     __WeaklyEqualityComparableWith &&     __PartiallyOrderedWith &&     requires(const std::remove_reference_t & a,              const std::remove_reference_

en.cppreference.com

 

공식 문서는 위쪽.

 

우리 눈에 익숙한 연산자들인 >, <, =, != ... 등등 말고, C++에서 공식적으로 지원하는 연산자가 C++20 부터 하나 더 생겼다.

 

<=>

 

이렇게 생긴 건데, 공식 명칭은 three-way comparison operator, 연산자 생긴 것이 우주선처럼 생겼다고 해서 spaceship operator 라고도 한다.

 

누가 이름 붙였냐...

 

 


 

사용법은 간단하다. a와 b 사이의 관계를 나타내는 연산자이고, a, b 두 값의 관계에 따라 결과값이 도출된다.

 

예전에 string 값을 비교하며 많이 사용했던 strcmp() 함수를 생각하면 이해가 빠를지도 모른다.

 

#include <iostream>

using namespace std;

int main()
{
	string s_a{"aaa"};
	string s_b{"aab"};

	strcmp(s_a.c_str(), s_b.c_str()) == 0;   // false
	strcmp(s_a.c_str(), s_b.c_str()) < 0;    // true
	strcmp(s_a.c_str(), s_b.c_str()) > 0;    // false



	int a{ 5 };
	int b{ 10 };

	(a <=> b) == 0;      // false
	(a <=> b) < 0;       // true
	(a <=> b) > 0;       // false

	return 0;
}

 

이렇게.

 

A <=> B 했을 때, 해당 값을 숫자로 바꾼 다음 뺀 느낌?

그 이후에 이 값이 음수인가, 0인가, 양수인가를 확인할 수 있게 된다.

 

 

 

 

 

만약 두 개가 다른 타입이라면, C++ conversion rule에 따라 type이 변경 된 다음 서로의 값을 비교하게 된다.

#include <iostream>

using namespace std;

int main()
{
	int a{ 5 };
	double b{ 5 };

	cout << ((a <=> b) == 0);      // false
	cout << ((a <=> b) < 0);       // true
	cout << ((a <=> b) > 0);       // false

	return 0;
}

 

 

 

conversion rule로 변경할 수 없는 값이라면?

 

error!

 

 

 

추가로, 저 삼항 연산자의 return값은 int처럼 사용하긴 하지만, 정확히 말하면 int는 아니고

std::strong_ordering / std::weak_ordering / std::partial_ordering 중 하나이다.

 

 

다만 type이 저렇다는거지, 해당 구조체 내부에 >, <, == 등의 연산자가 전부 overloading 되어 있기 때문에 사용할 때는 편하게 사용하면 된다.

 

 

 

* 잘못된 정보는 알려주시면 감사한 마음으로 수정하겠습니다.

 

 

반응형