[英]Is there a portable way to know if uintptr_t is defined in stdint.h?
前言:我想将指针转换为整数类型,例如检查对齐。 uintptr_t
似乎是正确的类型,但它仅在C中保证,而不是在C ++(或C ++ 11)中保证
对于以下代码:
#include <stdint.h>
#ifndef I_WONDER_IF_UINTPR_T_IS_DEFINED
typedef unsigned long uintptr_t;
#endif
template <typename T>
bool isAligned(unsigned char* p) ///Checks alignment with respect to some data type
{
return !((uintptr_t) p % sizeof(T));
}
template bool isAligned<uint16_t>(unsigned char* p);
template bool isAligned<uint32_t>(unsigned char* p);
template bool isAligned<uint64_t>(unsigned char* p);
2个问题:
I_WONDER_IF_UINTPR_T_IS_DEFINED
,我可以使用一个神奇而有保障的单词吗? unsigned long
而忘记它吗? 生成的程序集(当uintptr_t可用时): http : //goo.gl/4feUNK
注1:我知道比在C ++ 11中我应该使用alignof
代替sizeof
注2:我知道这个讨论: <cstdint> vs <stdint.h>
通常,* nix上的可移植构建系统倾向于使用“autotools”方法来测试编译包含相关类型的普通文件,如果它编译,你知道你有这种类型。 如果你想要更简单的东西,你可以(a)假设uintptr_t
即使在C ++中也可用(可能是合理的),或者(b)使用unsigned long long
然后:
static_assert(sizeof(unsigned long long) >= sizeof(void*), "oops");
如果你真的想在包含<stdint.h>
的情况下使用不提供uintptr_t
的实现,请考虑使用uintmax_t
,并使用static_assert
以确定是否合适(您已经建立了可能处于愚蠢的设置,因此它可能太小):
#include <stdint.h>
static_assert(sizeof(uintmax_t) >= sizeof(void*), "need a bigger unsigned type.");
// Add code using `uintmax_t` to round-trip data-pointers here
但有两个不利因素:
uintmax_t
可能不是uintptr_t
,对于重载解析和链接很重要。 uintmax_t
可能比必要的大。 我知道这是很老了,但是,如何使用UINTPTR_MAX
您I_WONDER_IF_UINTPR_T_IS_DEFINED
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.