小编BHO*_*HOS的帖子

如何在C++中通过reinterpret_cast将非常量变量转换为常量静态整型类成员变量?

我正在读一本关于为微控制器编写现代 C++ 代码的书,书名为“实时 C++”。我正在尝试自己编写书中的代码。然而,在复制书中的代码并尝试构建它时,我收到了以下编译错误:

错误 C2131:表达式未求值为常量。
消息:遇到非常量(子)表达式

我插入了下面代码的相关部分:

#include <cstdint>
#include <iomanip>
#include <iostream>
namespace mcal
{
  namespace reg
  {
    // Simulate the transmit and receive hardware buffers on the PC.
    std::uint8_t dummy_register_tbuf;
    std::uint8_t dummy_register_rbuf;
  }
}

class communication
{
  private:
    static constexpr std::uint8_t* tbuf = reinterpret_cast<std::uint8_t*>(&mcal::reg::dummy_register_tbuf); 
    static constexpr std::uint8_t* rbuf = reinterpret_cast<std::uint8_t*>(&mcal::reg::dummy_register_rbuf);
};

/* rest of the nonrelated code */
Run Code Online (Sandbox Code Playgroud)

该错误指示发生转换的这两行。我知道我们尝试使用 static constexpr 整型类成员变量,因为这可以确保对它们进行优化(不断折叠)。我认为发生错误是因为我们尝试将非常量变量设置为常量变量,但我肯定是错的。因此,我恳请您向我解释一下这里真正的问题是什么以及作者为什么会犯这样的错误(如果这是一个错误)。另外,如果您另外指出正确的铸造方法,我将不胜感激。非常感谢。

c++ reinterpret-cast constexpr

5
推荐指数
1
解决办法
142
查看次数

标签 统计

c++ ×1

constexpr ×1

reinterpret-cast ×1