일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
- 디버깅
- 아두이노
- buildroot
- STM32
- GPIO
- USART
- 라즈베리파이
- Visual Studio Code
- avr-gcc
- nucleo
- QEMU
- Visual Studio
- Debugging
- Arduino
- yocto
- AArch64
- AVR
- bare metal
- Raspberry
- esp32
- BeagleBone
- Linux
- platformio
- 리눅스
- C++
- atmel
- vscode
- Debug
- raspberrypi
- UART
- Today
- Total
임베디드를 좋아하는 조금 특이한 개발자?
rel_ops를 통한 클래스 비교연산자 자동 구현 본문
저는 C++에서 클래스를 설계할 때 귀찮은 부분중 하나가 비교연산자를 구현이라고 생각합니다.
<,<=,>,>!,==,!= 6개나 되는 연산자를 오버로딩하는 것은 매우 번거롭죠.
하지만! 예상외로 C++에서는 <와 ==만 구현한다면 나머지 4개의 연산자를 자동적으로 오버로딩이 되는 기능을 제공해주고 있습니다. 사용 방법도 매우 간단하죠.!
간단한 예제를 만들어 설명드리도록 하겠습니다.
좌표를 나타내는 point를 나타내는 클래스가 있고 2개의 point 클래스를 비교를 하고 싶다고 가정하겠습니다.
2개의 point 클래스를 비교 할때 x의 좌표가 우선순위가 높고 y좌표가 우선순위가 낮게 설정하였습니다.
point.h
#pragma once
//rel_ops를 사용하기 위한 해더 파일
#include <utility>
// rel_ops가 자동적으로 비교 연산자 구연
using namespace std::rel_ops;
class point {
private:
int x, y;
public:
point(int x = 0, int y = 0) : x(x), y(y)
{}
bool operator<(const point& other) const {
if (x == other.x)
return y < other.y;
return x < other.x;
}
bool operator==(const point& other) const {
return (x == other.x) && (y == other.y);
}
};
main.c
#include <iostream>
#include "point.h"
using namespace std;
int main(void) {
point pt1(1, 2);
point pt2(2, 1);
cout << (pt1 > pt2) << endl;
return 0;
}
point.h 에서 #include <utility.h>에서 rel_ops; 네임스페이스를 using 하는 것만을 해결되었습니다.
main.c에서 > 연산자는 오버로딩하지 않았음에도 정상적으로 실행이 되는 것을 확인 할 수 있습니다.
참고 자료
https://cplusplus.com/reference/utility/rel_ops/
rel_ops - C++ Reference
123456 namespace rel_ops { template bool operator!= (const T& x, const T& y) { return !(x==y); } template bool operator> (const T& x, const T& y) { return y bool operator<= (const T& x, const T& y) { return !(y bool operator>= (const T& x, const T& y) { re
cplusplus.com
https://en.cppreference.com/w/cpp/utility/rel_ops/operator_cmp
std::rel_ops::operator!=,>,<=,>= - cppreference.com
template< class T > bool operator!=( const T& lhs, const T& rhs ); (1) (deprecated in C++20) template< class T > bool operator>( const T& lhs, const T& rhs ); (2) (deprecated in C++20) template< class T > bool operator<=( const T& lhs, const T& rhs ); (3)
en.cppreference.com
'C++' 카테고리의 다른 글
accumulate() 함수의 overflow 문제 해결 방법 (0) | 2025.01.21 |
---|