序言:我想将指针转换为整数类型,例如检查对齐。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>