c++ - reinterpret_cast with an integer literal is not a constexpr
问题描述
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;
}
解决方案
简而言之,如果您无法修改PORT
,则无法指定PORT
为constexpr
.
constexpr
表达式不能包含reinterpret_cast
。这是未定义的行为。请记住,在这种情况下, c 样式(int*)
转换为static_cast
或。reinterpret_cast
reinterpret_cast
鉴于您的示例,我不明白您为什么不使用const
.
const int *p = PORT;
推荐阅读
- python - 如何读取 python 结构的结果?
- javascript - 我可以将表单标记为与浏览器用户一样有效吗?
- sql - “每个 GROUP BY 表达式必须包含至少一个不是外部引用的列”和“分组集”
- flutter - Flutter - 画布中重叠线条的颜色
- javascript - 如何更改父母 jQuery 上的输入值
- python - python - 如何在python中将信号部分随机放置到时间序列中?
- c# - 为什么我的 Windows 服务似乎在旋转 CPU 内核
- asynchronous - 如何创建异步 Camel-kafka 消费者?
- r - 当我清除环境时,闪亮的代码可以工作,但会抛出对象'Year' not found 错误
- kubernetes - Kubernetes 网络策略和外部负载均衡器