I want to use constexpr
instead of #define
s wherever possible, for type safety and namespace features.
Unfortunately, I get this error: 'reinterpret_cast<SPI_TypeDef*>(1073756160)' is not a constant expression
when trying.
#include <stm32f0xx.h> // #defines SPI2 as pointer to a struct of volatile unsigned ints
constexpr auto myPort = SPI2;
I'm not looking for an explanation of why reinterperet_cast
cannot be used in a constexpr
.
What is the modern C++ way to have a constexpr pointer to some memory mapped hardware?
One reason for this is to use these constexpr
values in templated code.
constexpr
code wasn't invented so that you could avoid using#define
s; it's there so that you can do certain things with expressions that you couldn't otherwise. You can passconstexpr
pointers or integers as template parameters, for example, since they are constant expressions.Basically, the primary purpose of any
constexpr
variable or function is to be able to be used within compile-time programming. So to declare a variable to beconstexpr
is to say "this is a compile-time constant and it's reasonable to use it at compile-time."A pointer whose value is an arbitrary address cannot be used at compile-time. So marking such a pointer as a compile-time value is a contradiction. So you're not allowed to do it.
constexpr
pointers are required to be real pointers, which are either null pointers or point to actual objects. Not to arbitrary addresses.