728x90
1. 개요
오늘은 C++ 20에 나온 SpaceShip Operator에 대해 알아보도록 하겠습니다.
2. SpaceShip Operator?
C++ 20에 추가된 비교 연산자 이며 아래와 같이 비교 연산을 위해서는 여러 연산자를 각각 구현을 해야했습니다.
a == b
a != b
a < b
a > b
a <= b
a >= b
이러면 매우 많은 연산자를 구현해야하기 때문에 코드가 길어 좋지 못한 코드가 생깁니다.
bool operator < (const TestSpaceShip& _Test)const {}
bool operator <= (const TestSpaceShip& _Test)const {}
bool operator > (const TestSpaceShip& _Test)const {}
bool operator >= (const TestSpaceShip& _Test)const {}
bool operator == (const TestSpaceShip& _Test)const {}
bool operator != (const TestSpaceShip& _Test)const {}
이런식으로 말이지요
하지만 C++에서 다음과 같이 operator을 구현 (아니면 직접 구현) 하면 됩니다.
3. <=>
<=> 이걸 보면서 뭔 이딴 비교 연산자가 있나 생각했습니다. 이게 우주선 처럼 생겨서 SpaceShip Operator라고 합니다.
auto operator<=>(const Type&) const = default;
이렇게 구현하거나
#include <compare>
std::strong_ordering operator<=>(const MyClass& other) const
{
if (value < other.value) return std::strong_ordering::less;
if (value > other.value) return std::strong_ordering::greater;
return std::strong_ordering::equal;
}
직접 구현을 해도 됩니다.
3. 실제 동작
#include<iostream>
using namespace std;
#include <compare>
struct Point
{
int x;
int y;
auto operator<=>(const Point&) const = default;
};
int main()
{
Point a{ 1,2 };
Point b{ 1,3 };
a < b; // OK
a == b; // OK
a >= b; // OK
return 0;
}
참고로 a b를 비교할때 먼저 나온 변수를 비교합니다.
(근데 ==은 둘 다 ==이여지만 가능한거같습니다.)
4. 대표적인 반환 타입
✅ strong_ordering
완전한 순서 (int 같은 것)
std::strong_ordering
✅ weak_ordering
동치지만 완전 동일하지는 않음
(예: 대소문자 무시 문자열 비교)
✅ partial_ordering
정렬 불가능한 경우 존재
(예: float NaN)
5. 실무에서 사용할까?
언리얼에서는 4버전은 C++14 5버전은 C++17버전을 사용합니다.
다만 4버전에서 TVariant를 사용은 하긴합니다. C++17에 나왔는데
'개발자 면접 공부 > C-C++' 카테고리의 다른 글
| 정규 표현식 (0) | 2025.12.18 |
|---|---|
| C++ Placement New에 대한 공부 (0) | 2025.11.27 |
| 정적 링킹 vs 동적 링킹 (0) | 2024.07.04 |
| 템플릿(Template) (1) | 2024.07.01 |
| C++ 11 범위기반 for문 (for each) (0) | 2024.06.16 |