无符号长的类型与Windows上的uint32_t和uint64_t不同(VS2010)

tbl*_*her 6 c++ visual-c++ visual-c++-2010

在Windows 7,32位下的Visual Studio 2010上,unsigned long似乎是uint32_t和uint64_t的不同类型.请参阅以下测试程序:

#include <stdint.h>
#include <stdio.h>

template<class T, class U>
struct is_same_type
{
    static const bool value = false;
};
template<class T>
struct is_same_type<T, T>
{
    static const bool value = true;
};

#define TO_STRING(arg)        TO_STRING_IMPL(arg)
#define TO_STRING_IMPL(arg)   #arg

#define PRINT_SAME_TYPE(type1, type2) printf("%s (size=%d) %s %s (size=%d)\n", \
    TO_STRING(type1), int(sizeof(type1)), \
    is_same_type<type1, type2>::value ? "==" : "!=", \
    TO_STRING(type2), int(sizeof(type2)))


int main(int /*argc*/, const char* /*argv*/[])
{
    PRINT_SAME_TYPE(uint32_t, unsigned long);
    PRINT_SAME_TYPE(uint64_t, unsigned long);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望它能打印出来

uint32_t (size=4) != unsigned long (size=8)
uint64_t (size=8) == unsigned long (size=8)
Run Code Online (Sandbox Code Playgroud)

(我在x86_64 Linux上获得)或

uint32_t (size=4) == unsigned long (size=4)
uint64_t (size=8) != unsigned long (size=4)
Run Code Online (Sandbox Code Playgroud)

当然假设长度不超过64位.

然而,在Windows上,我感到莫名其妙

uint32_t (size=4) != unsigned long (size=4)
uint64_t (size=8) != unsigned long (size=4)
Run Code Online (Sandbox Code Playgroud)

这意味着有两种不同的32位无符号类型.这是否允许C++标准?或者这是Visual C++编译器中的错误?

Jam*_*lis 7

有两种不同的32位无符号类型

是的,有.二者intlong用32位表示.

这是否允许C++标准?

是.规范说明(C++11§3.9.1[basic.fundamental]/2):

有五种标准符号整数类型:signed char,short int,int,long int,和long long int.在此列表中,每种类型至少提供与列表中前面的存储一样多的存储空间.

对于每个标准有符号整数类型,存在相应的(但不同的)标准无符号整数类型...每个类型占用相同的存储量并且具有与对应的有符号整数类型相同的对齐要求

请注意,尽管int并且long由相同数量的位表示并且它们仍然是不同的类型(因此,例如,在重载分辨期间它们被区别对待).