samedi 25 janvier 2020

Why is reinterpret_cast not constexpr?

Consider the following snippet:

static constexpr uint8_t a = 0;
static constexpr const int8_t *b = reinterpret_cast<const int8_t *>(&a);

This fails to compile with error: a reinterpret_cast is not a constant expression, because the C++ standard forbids using reinterpret_cast in constexpr.

However compilation succeeds if I want to store the value b in PROGMEM (for AVR microcontrollers):

static constexpr uint8_t a = 0;
static const int8_t PROGMEM *const b = reinterpret_cast<const int8_t *>(&a);

In this case the compiler is able to prove that the expression reinterpret_cast<const int8_t *>(&a) is compile-time constant, since it inserts its result (an address pointing to some byte containing a zero) into program space in the binary:

_ZL1g:
  .zero   1
  .section        .progmem.data,"a",@progbits
  .type   _ZL1b, @object
  .size   _ZL1b, 2
_ZL1b:
  .word   _ZL1g

Also, my understanding is that reinterpret_cast is a compile-time directive. So how come it can't be used inside a constexpr?

Aucun commentaire:

Enregistrer un commentaire