reinterpret_cast 带有整数文字不是 constexpr
reinterpret_cast with an integer literal is not a constexpr
下面的代码在 gcc
和 clang
中都不编译。两者都抱怨说,reinterpret_cast
到 int*
不是 constexpr
。
我该如何解决这个问题?请注意,我无法修改宏 PORT
,因为它是在第 3 方库 (avr
) 中定义的。
#include <iostream>
#define PORT ((int *)(0x20))
constexpr int *p = PORT; // does not compile
int main() {
std::cout << (uintptr_t) p << "\n";
return 0;
}
简单地说,如果您不能修改 PORT
,您就不能将 PORT
指定为 constexpr
。
constexpr
表达式不能包含 reinterpret_cast
。这是未定义的行为。请记住,像 (int*)
这样的 c 风格转换被简化为 static_cast
或 reinterpret_cast
,在这种情况下,reinterpret_cast
.
鉴于你的例子,我不明白你为什么不直接使用 const
。
const int *p = PORT;
下面的代码在 gcc
和 clang
中都不编译。两者都抱怨说,reinterpret_cast
到 int*
不是 constexpr
。
我该如何解决这个问题?请注意,我无法修改宏 PORT
,因为它是在第 3 方库 (avr
) 中定义的。
#include <iostream>
#define PORT ((int *)(0x20))
constexpr int *p = PORT; // does not compile
int main() {
std::cout << (uintptr_t) p << "\n";
return 0;
}
简单地说,如果您不能修改 PORT
,您就不能将 PORT
指定为 constexpr
。
constexpr
表达式不能包含 reinterpret_cast
。这是未定义的行为。请记住,像 (int*)
这样的 c 风格转换被简化为 static_cast
或 reinterpret_cast
,在这种情况下,reinterpret_cast
.
鉴于你的例子,我不明白你为什么不直接使用 const
。
const int *p = PORT;