[英]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.