考虑以下代码片段:
static constexpr uint8_t a = 0;
static constexpr const int8_t *b = reinterpret_cast<const int8_t *>(&a);
由于C++标准禁止在 constexpr
中使用reinterpret_cast
,因此出现错误: error: a reinterpret_cast is not a constant expression
。
然而,如果我想要将值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)
是编译时常量,因为它将其结果(指向某个包含零的字节的地址)插入二进制程序空间中:在此情况下,编译器能够证明表达式
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
中使用呢?
static_cast<uint8_t*>(static_cast<void*>(ptr))
- Treviño