模板函数min/max与Visual C++中的 min/max宏冲突

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhuangshn/archive/2010/04/28/5537499.aspx

1. 错误输出

    .\zlibrary\ui\src\win32\w32widgets\W32VBorderBox.cpp(114) : error C2589: “(”: “::”右边的非法标记
    .\zlibrary\ui\src\win32\w32widgets\W32VBorderBox.cpp(114) : error C2059: 语法错误 : “::”
2. 错误代码举例

   view plaincopy to clipboardprint?
size.Width = std::max(size.Width, elementSize.Width); 
size.Width = std::max(size.Width, elementSize.Width);

3. 函数模板max  

   view plaincopy to clipboardprint?
template<class _Ty> inline  
    const _Ty& (__CLRCALL_OR_CDECL max)(const _Ty& _Left, const _Ty& _Right)  
    {   // return larger of _Left and _Right  
    return (_DEBUG_LT(_Left, _Right) ? _Right : _Left);  
    } 
template<class _Ty> inline
 const _Ty& (__CLRCALL_OR_CDECL max)(const _Ty& _Left, const _Ty& _Right)
 { // return larger of _Left and _Right
 return (_DEBUG_LT(_Left, _Right) ? _Right : _Left);
 }   

   注:模板就是实现代码重用机制的一种工具,它可以实现类型参数化,即把类型定义为参数, 从而实现了真正的代码可重用性。模版可以分为两类,一个是函数模版,另外一个是类模版。

4. 错误原因

   函数模板max与Visual C++中的全局的宏max冲突。

5. 解决办法

    第一种办法:设置项目属性,在预定义处理器中添加定义NOMINMAX来禁止使用Vsual C++的min/max宏定义。

                       项目属性   ——> C/C++ ——> 预处理器 ——> 预处理器定义 (此处添加预定义编译开关   NOMINMAX)

    第二种办法: 加上括号,与Vsual C++的min/max宏定义区分开

                       view plaincopy to clipboardprint?
size.Width = std::max(size.Width, elementSize.Width);   

posted on 2011-03-12 16:56  Livid  阅读(1350)  评论(0编辑  收藏  举报

导航