gpt4 book ai didi

c++ - 有没有一种可移植的方法来知道 uintptr_t 是否在 stdint.h 中定义?

转载 作者:太空狗 更新时间:2023-10-29 21:19:50 24 4
gpt4 key购买 nike

序言:我想将指针转换为整数类型,例如检查对准。 uintptr_t 似乎是正确的类型,但是 it is guaranteed only in C, not in C++ (or 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>

最佳答案

如果您真的想使用不提供 uintptr_t 的实现当包含 <stdint.h> 时, 考虑使用 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

不过有两个缺点:

  1. uintmax_t可能不是 uintptr_t ,对于过载解析和链接很重要。
  2. uintmax_t可能比必要的要大。

关于c++ - 有没有一种可移植的方法来知道 uintptr_t 是否在 stdint.h 中定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26160068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com