具有整数文字的reinterpret_cast不是constexpr [英] reinterpret_cast with an integer literal is not a constexpr

查看:105
本文介绍了具有整数文字的reinterpret_cast不是constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码既不能在 gcc 中也不能在 clang 中进行编译。都抱怨说, reinterpret_cast int * 不是 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.

如何解决该问题?请注意,我无法修改在第三方库( avr )中定义的宏 PORT

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

Put simply, if you cannot modify PORT you cannot specify PORT as constexpr.

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

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.

给出您的示例,我不明白为什么不只使用 const

Given your example, I don't see why you wouldn't just use const.

const int *p = PORT;

这篇关于具有整数文字的reinterpret_cast不是constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆