define에 의한 문제를 해결할 때 참고할 만한 내용이다.
문제는... 아래 코드는 컴파일 되지 않는다는 것이다.
#include <limits>
#include <windows.h>
void main()
{
std::numeric_limits< float >::max();
}
에러 메세지를 보면...
1>d:\programming\test\main.cpp(5) : warning C4003: not enough actual parameters for macro 'max'
1>d:\programming\test\main.cpp(5) : error C2589: '(' : illegal token on right side of '::'
1>d:\programming\test\main.cpp(5) : error C2143: syntax error : missing ';' before '::'
이유는 windef.h에 정의된 다음과 같이 min, max 가 define되어 있기 때문이다.
#ifndef NOMINMAX
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#endif /* NOMINMAX */
여기를 보면 3가지 해결 방안이 나온다.
1. 괄호로 싸버린다.
std::numeric_limits< float >::max(); -> (std::numeric_limits< float >::max)();
2. undefine 해버린다.
#include <limits>
#include <windows.h>
#undef max
void main()
{
std::numeric_limits< float >::max();
}
3. NOMINMAX를 define한다.
#define NOMINMAX
#include <limits>
#include <windows.h>
void main()
{
std::numeric_limits< float >::max();
}
MS MVP님께서 추천하는 방법은 다음과 같다.
#define NOMINMAX
#include <windows.h>
#include <limits>
#include <algorithm>
template< typename T >
inline T max(const T & a, const T & b) { return std::max(a, b); }
template< typename T >
inline T min(const T & a, const T & b) { return std::min(a, b); }
void main()
{
std::numeric_limits< float >::max();
}