如何在编译时判断一个~类型~是否为unsigned
在这个贴子中:VIA笔试题,怎么写程序判断一个数是unsigned int还是int?(http://community.csdn.net/Expert/topic/4359/4359119.xml?temp=.8052027)
在该贴中我曾经提出“C++是静态编译的,在编译时就应已经知道变量的类型啊?”,后来在一次编程实践中,我发现在标准库有太多的typedef,你可能一不小心写下这样的代码:
#ifdef USE_UNSIGNED_INT
typedef unsigned int size;
#else
typedef int size;
#endif
latter in the program:
size i = XXX;
for (; i >=0 ; i--) //problematic, if the i is the unsigned it!!!
{
}
这段代码有问题的!如果size被定义成无符号类型,那么这将是一个无限循环!昨天我去各论坛问了下“如何在编译时判断一个~类型~是否为unsigned”,现在已经找到方法了:
#include <boost/static_assert.hpp>
#include <limits>
BOOST_STATIC_ASSERT(std::numeric_limits<size>::is_signed);
该方法会在编译时判断size是否为有符号的类型,如无符号则出错!