reinterpret_cast with an integer literal is not a constexpr

亡梦爱人 提交于 2020-01-06 06:42:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!