【发布时间】:2020-05-11 18:35:10
【问题描述】:
考虑以下 sn-p:
static constexpr uint8_t a = 0;
static constexpr const int8_t *b = reinterpret_cast<const int8_t *>(&a);
使用error: a reinterpret_cast is not a constant expression 编译失败,因为the C++ standard forbids 在constexpr 中使用了reinterpret_cast。
但是,如果我想将值 b 存储在 PROGMEM 中(对于 AVR 微控制器),编译会成功:
static constexpr uint8_t a = 0;
static const int8_t PROGMEM *const b = reinterpret_cast<const int8_t *>(&a);
在这种情况下,编译器能够证明表达式reinterpret_cast<const int8_t *>(&a) 是编译时常量,因为它将其结果(指向包含零的某个字节的地址)插入到二进制程序空间中:
_ZL1g:
.zero 1
.section .progmem.data,"a",@progbits
.type _ZL1b, @object
.size _ZL1b, 2
_ZL1b:
.word _ZL1g
另外,我的理解是reinterpret_cast 是一个编译时指令。那怎么不能在constexpr里面使用呢?
【问题讨论】:
-
不是很好,但解决方法是从 void 传递...所以
static_cast<uint8_t*>(static_cast<void*>(ptr))
标签: c++ c++11 avr constexpr reinterpret-cast