用于测试整数类型是有符号还是无符号的宏

您将如何编写(在C / C ++中)一个宏来测试整数类型(作为参数给出)是签名还是未签名?


       #define is_this_type_signed(my_type)...

如果您想要的是一个简单的宏,这应该可以解决问题:

#define is_type_signed(my_type) (((my_type)-1) < 0) 

在C ++中,使用std::numeric_limits::is_signed

 #include  std::numeric_limits::is_signed - returns true std::numeric_limits::is_signed - returns false 

请参阅http://msdn.microsoft.com/en-us/library/85084kd6(VS.80).aspx 。

如果你想要一个宏,那么这应该做的伎俩:

 #define IS_SIGNED( T ) (((T)-1)<0) 

基本上,将-1转换为您的类型并查看它是否仍为-1。 在C ++中,您不需要宏。 只需#include 和:

 bool my_type_is_signed = std::numeric_limits::is_signed; 

您的要求并不是最好的,但如果您想要将定义合并在一起,则可以选择以下选项:

 #define is_numeric_type_signed(typ) ( (((typ)0 - (typ)1)<(typ)0) && (((typ)0 - (typ)1) < (typ)1) ) 

但是,无论如何,这都不算或便携。

实际上我今天早些时候想知道同样的事情。 以下似乎有效:

 #define is_signed(t) ( ((t)-1) < 0 ) 

我测试过:

 #include  #define is_signed(t) ( ((t)-1) < 0 ) #define psigned(t) printf( #t " is %s\n", is_signed(t) ? "signed" : "unsigned" ); int main(void) { psigned( int ); psigned( unsigned int ); } 

打印:

 int is signed unsigned int is unsigned 

在C ++中,您可以:

 bool is_signed = std::numeric_limits::is_signed; 

numeric_limits在标头中​​定义。

虽然typeof目前不是合法的C ++,但你可以使用模板推理。 请参阅以下示例代码:

 #include  #include  template  bool is_signed(const T& t) { return std::numeric_limits::is_signed; } int main() { std::cout << is_signed(1) << " " << is_signed((unsigned char) 0) << " " << is_signed((signed char) 0) << std::endl; } 

此代码将打印出来

  1 0 1 

对于c ++,有boost :: is_unsigned 。 我很好奇为什么你需要它,恕我直言的原因很少。

更“现代”的方法是使用type_traits

 #include  #include  int main() { std::cout << ( std::is_signed::value ? "Signed" : "Unsigned") < 

你可以通过模板function更好地做到这一点,减少宏观讨厌的业务。

  template  bool IsSignedType() { // A lot of assumptions on T here T instanceAsOne = 1; if (-instanceAsOne > 0) { return true; } else { return false; } } 

原谅格式……

我会尝试一下,看看它是否有效……

在C中,你不能编写一个宏,它可以处理尚未知的typedef的基本整数类型。

在C ++中,只要您的类型是基本整数类型或基本整数类型的typedef,就可以。 这是你在C ++中做的事情:

 template  struct is_signed_integer { static const bool value = false; }; template <> struct is_signed_integer { static const bool value = true; }; template <> struct is_signed_integer { static const bool value = true; }; template <> struct is_signed_integer { static const bool value = true; }; template <> struct is_signed_integer { static const bool value = true; }; // assuming your C++ compiler supports 'long long'... template <> struct is_signed_integer { static const bool value = true; }; #define is_this_type_signed(my_type) is_signed_integer::value