std::min and std::max

在微軟的 "windows.h" 內以 macro 的型式, 預先定義了 min 和 max
#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 */


這原本是方便開發者開發程式,但是在 STL 十分普遍地被使用的現在,卻導致我們不能很順利的使用 STL 所提供的 std::min, std::max,造成 VC 2005 會抱怨

1>d:\visualstudioprojects\test\main.cpp(252) : error C2589: '(' : illegal token on right side of '::'
1>d:\visualstudioprojects\test\main.cpp(252) : error C2143: syntax error : missing ';' before '::'

解決的方法之一就是就是在開頭的地方加入

#define NOMINMAX

不然就是將 std::max 用括號包起來

int x = (std::max)(a, b);

這樣 min, max 就不會被 preprocessor 當成 macro 處理


參考:
http://heifner.blogspot.com/2008/02/stdmin-and-stdmax.html

0 意見 :: std::min and std::max

張貼留言