簡體   English   中英

從 char* 到 uintptr_t 的轉換

[英]conversion from char* to uintptr_t

我有以下代碼並出現編譯錯誤:

#include <cstddef>
#include <cstdint>

#define CHECK_ALIGN(ptr, alignment)                       \
  do{                                                     \
    constexpr size_t status                               \
       = reinterpret_cast<uintptr_t>(ptr) % alignment;    \
    static_assert(status == 0, "ptr must be aligned");    \
  }while(0)  

int main(int argc, char** argv) {
  char c;
  int i;
  long l ;
  float f;
  CHECK_ALIGN(&c, sizeof(c));
  CHECK_ALIGN(&i, sizeof(i));
  CHECK_ALIGN(&l, sizeof(l));
  CHECK_ALIGN(&f, sizeof(f));
  return 0;
}

錯誤:在常量表達式中從指針類型“char*”轉換為算術類型“uintptr_t”{又名“long unsigned int”}

將那些指針類型轉換為進行某些算術運算的正確類型是什么?

status不能是constexpr ,因為ptr的值在編譯時是未知的。 此外,出於同樣的原因, static_assert()需要替換為assert()

#include <cstddef>
#include <cstdint>
#include <cassert>

#define CHECK_ALIGN(ptr, alignment)                       \
  do{                                                     \
    const size_t status                                   \
       = reinterpret_cast<uintptr_t>(ptr) % alignment;    \
    assert(status == 0);                                  \
  } while(0)  

int main(int argc, char** argv) {
  char c;
  int i;
  long l ;
  float f;
  CHECK_ALIGN(&c, sizeof(c));
  CHECK_ALIGN(&i, sizeof(i));
  CHECK_ALIGN(&l, sizeof(l));
  CHECK_ALIGN(&f, sizeof(f));
  return 0;
}

Godbolt: https://godbolt.org/z/GrWdE3sGK

或者,您可以像這樣使用constexpr表達式:

#include <cstddef>
#include <cstdint>

#define CHECK_ALIGN(value, alignment) \
    static_assert(alignof((value)) % alignment == 0, #value " must be aligned");    

int main(int argc, char** argv) {
  char c;
  int i;
  long l ;
  float f;
  CHECK_ALIGN(c, sizeof(c));
  CHECK_ALIGN(i, sizeof(i));
  CHECK_ALIGN(l, sizeof(l));
  CHECK_ALIGN(f, sizeof(f));
  return 0;
}

Godbolt: https://godbolt.org/z/fMfY3P9bd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM