问题
The code below does not compile neither in gcc
nor in clang
. Both complain that, the reinterpret_cast
to int*
is not a constexpr
.
How can I work-around the problem? Note that I cannot modify the macro PORT
, as it is defined in a 3-rd party library (avr
).
#include <iostream>
#define PORT ((int *)(0x20))
constexpr int *p = PORT; // does not compile
int main() {
std::cout << (uintptr_t) p << "\n";
return 0;
}
回答1:
Put simply, if you cannot modify PORT
you cannot specify PORT
as constexpr
.
A constexpr
expression cannot contain reinterpret_cast
. It is undefined behavior. Keep in mind that a c-style cast like (int*)
is reduced to either static_cast
or reinterpret_cast
, in this case, reinterpret_cast
.
Given your example, I don't see why you wouldn't just use const
.
const int *p = PORT;
来源:https://stackoverflow.com/questions/54169791/reinterpret-cast-with-an-integer-literal-is-not-a-constexpr