简体   繁体   English

从 char* 到 uintptr_t 的转换

[英]conversion from char* to uintptr_t

I have the following code and get a compiling error:我有以下代码并出现编译错误:

#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;
}

error: conversion from pointer type 'char*' to arithmetic type 'uintptr_t' {aka 'long unsigned int'} in a constant expression错误:在常量表达式中从指针类型“char*”转换为算术类型“uintptr_t”{又名“long unsigned int”}

What is the proper type to convert to for those pointer type to do some arithmetic?将那些指针类型转换为进行某些算术运算的正确类型是什么?

status cannot be constexpr because the value of ptr is not known at compile time. status不能是constexpr ,因为ptr的值在编译时是未知的。 Also, static_assert() needs to be replaced with assert() for the same reason.此外,出于同样的原因, 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 Godbolt: https://godbolt.org/z/GrWdE3sGK

Alternatively, you could use constexpr expressions like this:或者,您可以像这样使用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 Godbolt: https://godbolt.org/z/fMfY3P9bd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM