std::abs()真的消失了吗?
今天在VC环境下验证一个解决名称冲突的小程序时,突然发现一个疑问:std::abs()消失了吗?
代码如下:
//====================================
#include<iostream>
using namespace std;
//-------------------------------------
int abs(int a){ return a>0 ? a : -a; }
//-------------------------------------
int main(){
int a = abs(-5);
int b = std::abs(-5);
std::cout<<a<<std::endl<<b<<std::endl;
return 0;
}
//====================================
运行之后居然弹出:
errors:'abs'is not a number of 'std'!!!
晕死!!!
难道std::abs()真的消失了吗???
试着变动一下:
//====================================
#include<iostream>
using namespace std;
//------------------------------------
namespace std {
/*#ifdef abs
#undef abs
#endif*/
template < class T >
inline const T & abs ( const T & a )
{
const T & retval = a < 0 ? -a : a;
return retval;
}
}
//-------------------------------------
int abs(int a){ return a>0 ? a : -a; }
//-------------------------------------
int main(){
int a = abs(-5);
int b = std::abs(-5);
std::cout<<a<<std::endl<<b<<std::endl;
return 0;
}
//====================================
顺利pass!难道是要显式调用命名空间或者类似重载一样的操作吗?
强大的STL怎么会把std::abs()弄丢了呢?
由此,我想到了std::min()和std::max(),居然也同样,做类似变动就OK了.
我把这个问题提出来,希望能起到一个抛砖引玉的作用,与大家共同探讨.