infinite 이미지좀 가져올라고 검색했더니 가수 인피니트가 뜬다....짜증난다..
우선 C++에는 무한대 타입이 존재한다.
<limits>
의 std::numeric::limits::infinity()
이다.
하지만 이 메소드는 실수타입에서만 제대로 동작한다. 정수타입에서는 0을 반환하기때문에..(0은 무한대가 아니다..알겠지만)
#include <iostream>
#include <limits>
using namespace std;
int main() {
int max = numeric_limits<int>::max();
int inf = numeric_limits<int>::infinity();
if (max < inf){
cout << "what?" << endl;
}
cout << inf << '\t' << max << endl;
}
0 2147483647
계속하려면 아무 키나 누르십시오 . . .
위 소스처럼 동작하면 안된다.
우리는 어떤 숫자 타입에서도 동작하는 infinite를 구현할 수 있다.
C언어에서는 아쉽지만 C++에서 처럼 연산자 오버로딩이 없으므로, 완벽하게 지원할 순 없다.
#pragma once
#ifndef MATH_INFINITE_H_7DE_6_B_INCLUDED
#define MATH_INFINITE_H_7DE_6_B_INCLUDED
#ifdef __cplusplus
const class{ //this object is const object
//infinite is left value
public:
template<typename T>
bool operator==(T&& type)const{
return false;
}
template<typename T>
bool operator!=(T&& type)const{
return true;
}
template<typename T>
bool operator<(T&& type)const{
return false;
}
template<typename T>
bool operator<=(T&& type)const{
return false;
}
template<typename T>
bool operator>(T&& type)const{
return true;
}
template<typename T>
bool operator>=(T&& type)const{
return true;
}
}infinite = {};
using infinite_t = decltype(infinite);
//infinite is right value
template<typename T>
bool operator==(T type, const infinite_t& i){
return false;
}
template<typename T>
bool operator!=(T type, const infinite_t& i){
return true;
}
template<typename T>
bool operator<(T type, const infinite_t& i){
return true;
}
template<typename T>
bool operator<=(T type, const infinite_t& i){
return true;
}
template<typename T>
bool operator>(T type, const infinite_t& i){
return false;
}
template<typename T>
bool operator>=(T type, const infinite_t& i){
return false;
}
#else
//c language
#include<float.h>
#define infinite DBL_MAX
#endif //__cplusplus
#endif //MATH_INFINITE_H_7DE_6_B_INCLUDED
연산자 오버로딩을 알면 구현할 수 있는 간단한 예제이다.
2016년 6월 11일 글 등록
###References
http://en.cppreference.com/w/cpp/types/numeric_limits/infinity