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

时间:2020-03-05 18:54:01  来源:igfitidea点击:

我们将如何编写(在C / C ++中)用于测试整数类型(作为参数)是带符号还是无符号的宏?

#define is_this_type_signed (my_type) ...

解决方案

回答

在C ++中,使用std :: numeric_limits <type> :: is_signed

#include <limits>
std::numeric_limits<int>::is_signed  - returns true
std::numeric_limits<unsigned int>::is_signed  - returns false

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

回答

如果我们想要的是一个简单的宏,则可以做到这一点:

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

回答

对于c ++,有boost :: is_unsigned <T>。我很好奇为什么我们需要它,恕我直言,没有什么充分的理由。

回答

要求并不完全是最好的,但是如果我们想一起定义一个定义,则一个选择可能是:

#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 <stdio.h>

#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

回答

我们可以使用模板功能更好地做到这一点,减少宏观麻烦的业务。

template <typename T>
        bool IsSignedType()
        {
           // A lot of assumptions on T here
           T instanceAsOne = 1;

           if (-instanceAsOne > 0)
           {
               return true;
           }
           else
           {
               return false;
           }
}

原谅格式...

我会尝试一下,看看是否可行...

回答

在C ++中,我们可以执行以下操作:

bool is_signed = std::numeric_limits<typeof(some_integer_variable)>::is_signed;

numeric_limits在<limits>标头中​​定义。

回答

在C语言中,我们无法编写可用于基本整数类型的迄今未知typedef的宏。

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

template <typename T>
struct is_signed_integer
{
    static const bool value = false;
};

template <>
struct is_signed_integer<int>
{
    static const bool value = true;
};

template <>
struct is_signed_integer<short>
{
    static const bool value = true;
};

template <>
struct is_signed_integer<signed char>
{
    static const bool value = true;
};

template <>
struct is_signed_integer<long>
{
    static const bool value = true;
};

// assuming your C++ compiler supports 'long long'...
template <>
struct is_signed_integer<long long>
{
    static const bool value = true;
};

#define is_this_type_signed(my_type) is_signed_integer<my_type>::value

回答

如果我们想要一个宏,那么这应该可以解决问题:

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

基本上,将-1强制转换为类型,然后查看它是否仍为-1. 在C ++中,我们不需要宏。只需#include &lt;limits>和:

bool my_type_is_signed = std::numeric_limits<my_type>::is_signed;

回答

尽管typeof目前还不合法,但我们可以使用模板推导。请参见下面的示例代码:

#include <iostream>
#include <limits>

template <typename T>
bool is_signed(const T& t)
{
  return std::numeric_limits<T>::is_signed;
}

int main()
{
  std::cout << 
    is_signed(1) << " " << 
    is_signed((unsigned char) 0) << " " << 
    is_signed((signed char) 0) << std::endl;
}

此代码将打印

1 0 1