reinterpret_cast< volatile uint8_t *>(37)'不是常量表达式 [英] reinterpret_cast<volatile uint8_t*>(37)' is not a constant expression

查看:117
本文介绍了reinterpret_cast< volatile uint8_t *>(37)'不是常量表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcc不能编译下面的代码,而clang可以编译.我无法控制宏PORTB,因为它在第三方库(avr)中.

gcc fails to compile the code below, while clang compiles ok. I have no control on the macro PORTB, as it is in a 3rd party library (avr).

gcc错误吗?如何在gcc中解决该问题?作为一种解决方法,可以以某种方式创建一个预处理器宏,该宏从PORTB中提取数值吗?

Is it a gcc bug? How can I work around it in gcc? As a workaround is somehow possible to create a pre-processor macro which extracts the numerical value from PORTB?

请注意,这个问题与我之前的问题,即开发人员可以灵活地更改分配的rhs,从而避免使用reinterpret_cast.

Note this question is similar, but not identical to my previous question. It is also different from this question, where the developer has the flexibility to change the rhs of the assignment, thus avoiding the reinterpret_cast.

#include <iostream>
#include <cstdint>

#define PORTB (*(volatile uint8_t *)((0x05) + 0x20))

struct PortB {
    static const uintptr_t port = reinterpret_cast<uintptr_t>(&PORTB);
};

int main() {
    std::cout << PortB::port << "\n";
    return 0;
}

推荐答案

在编译期间似乎不允许 reinterpret_cast .因此,该编译器的较新版本仅更符合该语言.需要constexpr的地方不允许使用reinterpret_cast.

It seems reinterpret_cast is not allowed during compilation. Thus the newer version of the compiler simply is more conforming to the language. reinterpret_cast will not be allowed where a constexpr is required.

但是也许这些解决方法可能会有所帮助(用g ++ 9.2编译):

But maybe these workaround may help (compiles with g++ 9.2):

#include <iostream>
#include <cstdint>

#define PORTB (*(volatile uint8_t *)((0x05) + 0x20))

struct PortB {
    static uintptr_t port; 
};

uintptr_t PortB::port = reinterpret_cast<uintptr_t>(&PORTB);
const uintptr_t freePort = reinterpret_cast<uintptr_t>(&PORTB);
#define macroPort reinterpret_cast<uintptr_t>(&PORTB)

int main() {
    std::cout << PortB::port << "\n";
    std::cout << freePort << "\n";
    std::cout << macroPort << "\n";
    return 0;
}

这篇关于reinterpret_cast&lt; volatile uint8_t *&gt;(37)'不是常量表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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