I have an set of registers in MCU, and each of them has an unique adress. Imagine I have some register, that can be described with struct
struct RegisterDefinition{
u32 v1;
u32 v2;
u32 v3;
u32 v4;
};
I know (from MCU reference manual), the adress that one of the registers of that type has in memory
#define REGISTER_ADRESS 0x12345678
how can I constexpr initialize a pointer or reference of type RegisterDefinition, so I will be able to use that variable in constexpr constructors of other classes?
like
inline constexpr somedef* registerPointer = reinterpret_cast<somedef*>(REGISTER_ADRESS);
1 Answer 1
This is currently impossible. The language does not permit it. reinterpret_cast is not permitted in constant expressions and there is no workaround.
Store the integral value of the address in a constexpr variable instead and use e.g. a function that returns a pointer from that integral value by reinterpret_cast as late as possible in whatever calculation you want to do at compile-time.
Comments
Explore related questions
See similar questions with these tags.
&v1 == REGISTER_ADRESS?inline constexpr somedef* registerPointer = reinterpret_cast<somedef*>(REGISTER_ADRESS);orinline constexpr somedef& registerRef = *reinterpret_cast<somedef*>(REGISTER_ADRESS);reinterpret_castin constant expressions?