C++ 中位带地址的常量计算
我有以下类:
class Bit
{
void * bb_addr;
public:
constexpr Bit ( void * __data, int bitpos )
: bb_addr((void*)(0x22000000 + ((uint32_t)(__data) - 0x20000000) * 32 + bitpos * 4))
{}
};
在这个类定义中,我使用了 constexpr 构造函数 - 只是我想在编译时创建对象。这是要求,因为我是为微控制器编写的,我有相当多的程序代码内存,但 RAM 不多。 构造函数中的表达式是计算指定位的位带地址 - 我想在微控制器上使用此功能。 在另一个地方,此类的对象是用static constexpr
修饰符定义的,例如static constexpr Bit(&somevar, 15);
,所以最终它是闪存中的常量对象。这是我的目标。
不幸的是,由于非常量表达式,这被编译器拒绝。这让我考虑 - 在 C++ 17 中是否可以使用这种表达式,而保留整个初始化器 constexpr
?
我将尝试各种选项 - 通过模板化构造函数传递,或引用 __data
- 没办法。
G++ 表示从整数到指针的转换不是常量表达式。好的,我知道。但指针算术不允许乘法,因此即使转换为 unsigned char*
也无法解决问题。
所以我的问题是:可以在 C++ 的编译时计算复杂地址吗?根据Cortex-M3内核的位带地址计算?这在 C++17 标准中似乎是不可能的,但也许有人知道解决方案(甚至只有 G++ 接受)
I have following class:
class Bit
{
void * bb_addr;
public:
constexpr Bit ( void * __data, int bitpos )
: bb_addr((void*)(0x22000000 + ((uint32_t)(__data) - 0x20000000) * 32 + bitpos * 4))
{}
};
In this class definition I used constexpr constructor - simply I want to create object at compile time. This is requirement, because I write for microcontrollers, I have quite lot of program code memory, but not much of RAM.
Expression in constructor is calculation of bit-band address for specified bit - I would like to use this functionality on microcontroller.
In another place objects of this class are defined with static constexpr
modifier such as static constexpr Bit(&somevar, 15);
so finally it was constant object in FLASH memory. This is my target.
Unfortunately, this is rejected by compiler due to non constant expression. This make me consider - it is possible to use this kind of expression, in C++ 17 with leaving whole initializer constexpr
?
I'll try various options - passing by templated constructor, or reference to __data
- no way.
G++ says that casting from integer to pointer is not a constant expression. Ok, I know. But pointer arithmetic don't allow multiply, so even casting to unsigned char*
don't solve the problem.
So my question is: It is possible to calculate complex address in compile time in C++? According to bit-band address calculation of Cortex-M3 cores? It seems impossible in C++17 standard, but maybe someone know's the solution ( even only G++-accepted )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论