用模板方法来判断数据类型的符号
comp.lang.c++.moderated 上面有一篇帖子,说的是下面一段程序
#include <iostream>
#define OK
template<typename TIntegral>
struct is_signed
{
#ifdef OK
static const bool value = TIntegral(TIntegral() – 1) > 0 ? false :
true;
#else
static const bool value = ((TIntegral)0) – ((TIntegral)1) > ((TIntegral)
0) ? false : true;
#endif
};
template<typename TIntegral>
struct the_no
{
static const TIntegral value = TIntegral() – 1;
};
using std::cout;
template<typename T>
void display(void)
{
bool b = is_signed<T>::value;
cout << typeid(T).name();
if (b)
cout << ” is signed”;
else
cout << ” is UNsigned”;
cout << std::endl;
}
int main(void)
{
bool is_unsigned_char_signed = the_no<unsigned char>::value > 0 ?false : true;
unsigned char value = the_no<unsigned char>::value;
cout << “is_unsigned_char_signed is : “<< is_unsigned_char_signed << std::endl;
cout << “value is: ” << (short) value << std::endl;
typedef unsigned char UCHAR;
unsigned char n = UCHAR() -1;
cout << “UNSigned types:” << std::endl;
display<unsigned long long>();
display<unsigned long>();
display<unsigned int>();
display<unsigned short>();
display<unsigned char>();
cout << std::endl;
cout << “Signed types:” << std::endl;
display<signed long long>();
display<signed long>();
display<signed int>();
display<signed short>();
display<signed char>();
return 0;
}
为什么当OK宏未定义的时候,显示的结果如下:
UNSigned types:
unsigned __int64 is UNsigned
unsigned long is UNsigned
unsigned int is UNsigned
unsigned short is signed
unsigned char is signed
Signed types:
__int64 is signed
long is signed
int is signed
short is signed
signed char is signed
其中无符号的16位整型和无符号字符型都显示为有符号的了。而OK宏被定义的时候,却是正常的。作者很纳闷。为啥呢?
其实,作者此处绕了很多弯子,去用0和1做减法,看结果的符号来判断结果的类型,其实完全没有必要这么做,直接吧-1转换为目标类型,然后和零比较即可。而他认为能正常工作的,其实也只不过是在减法之后,又转换为目标类型了罢了。
现在来讨论 static const bool value = ((TIntegral)0) – ((TIntegral)1) > ((TIntegral)
0) ? false : true; 不能正常工作的原因吧,因为任何小于int的类型在计算时都已经提升为int了。呜呜。2008年过完了~
-
Articles
- March 2011
- November 2010
- September 2010
- August 2010
- June 2010
- April 2010
- March 2010
- December 2009
- September 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- August 2007
- June 2007
- May 2007
- April 2007
- March 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
- August 2006
- July 2006
- June 2006
- May 2006
- April 2006
- March 2006
- January 2006
-
Meta





