首页 > 解决方案 > 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;
}

标签: c++c++11constexpr

解决方案


简而言之,如果您无法修改PORT,则无法指定PORTconstexpr.

constexpr表达式不能包含reinterpret_cast。这是未定义的行为。请记住,在这种情况下, c 样式(int*)转换为static_cast或。reinterpret_castreinterpret_cast

鉴于您的示例,我不明白您为什么不使用const.

const int *p = PORT;

推荐阅读