1

对于类型安全和命名空间功能,我想尽可能使用constexpr而不是s。#define

不幸的是,我error: 'reinterpret_cast<SPI_TypeDef*>(1073756160)' is not a constant expression在尝试时得到了这个。

#include <stm32f0xx.h> // #defines SPI2 as pointer to a struct of volatile unsigned ints

constexpr auto myPort = SPI2;

不是在寻找解释为什么reinterperet_cast不能在constexpr.

将 constexpr 指针指向某些内存映射硬件的现代 C++ 方法是什么?

这样做的一个原因是constexpr在模板化代码中使用这些值。

4

3 回答 3

2

constexpr代码不是为了避免使用#defines 而发明的;它的存在是为了让你可以用其他方式无法做到的表达来做某些事情。例如,您可以将constexpr指针或整数作为模板参数传递,因为它们是常量表达式。

基本上,任何constexpr变量或函数的主要目的是能够在编译时编程中使用。所以声明一个变量constexpr就是说“这是一个编译时常量,在编译时使用它是合理的”。

不能在编译时使用其值为任意地址的指针。因此将这样的指针标记为编译时值是矛盾的。所以你不被允许这样做。constexpr指针必须是真正的指针,要么是空指针,要么是指向实际对象。不至任意地址。

于 2021-04-04T19:55:21.557 回答
0

这是不可能的。Evenstd::bit_cast在某些情况下可以reinterpret_cast在编译时进行模拟,但当涉及的类型之一是指针时,它就会失去其常量性。

于 2021-04-04T19:57:56.183 回答
0

就像其他答案已经说明的那样,任意指针是不可能的。

如果您要求的是“对于某些内存映射硬件的类型安全和命名空间功能 [...]”,为什么不直接使用

// assumed preconditions, since not provided in question
typedef struct {
  volatile unsigned int a;
  volatile unsigned int b;
} SPI_TypeDef;

SPI_TypeDef* SPI2 = (SPI_TypeDef*)0x12345678;

// actual answer
SPI_TypeDef* const myPort = SPI2;

这样,指向 struct SPI_TypeDef类型的某些数据的指针myPort是 const,但不是指向的结构。

const关键字通常是“左分配”。

于 2021-04-04T20:03:32.753 回答