我有一个模板类,它的第一个模板参数是一个 foo * 指针。我想用位于绝对地址的 foo 实例化其中之一,如下所示:
class foo
{
int baz;
};
template<foo *f> class bar
{
public:
bar() {}
void update() { /* ... */ }
};
// ....
#define FOO_ADDR ((foo *)0x80103400)
#define FOO_NULL ((foo *)0)
foo testFoo;
bar<FOO_ADDR> myFoo; // fails with non-integral argument
bar<FOO_NULL> huh; // compiles, I was surprised by this
bar<&testFoo> test; // compiles as expected (but not useful)
有谁知道是否可以不求助于链接器并使用外部链接定义 FOO_ADDR?
这是与 Keil ARM C/C++ 编译器版本 V5.06 更新 1(构建 61)一起使用的,我尝试打开 C++11 模式但是(除了在系统头文件中抛出大量新错误之外)它没有改变行为。
更新:这里是建议的解决方案(这次使用真正的代码)使用 int 转换
template<uint32 PORT, uint32 BIT, uint32 RATE> class LedToggle
{
uint32 mTicks;
uint32 mSetReset;
public:
LedToggle()
{
mTicks = 0;
mSetReset = 1 << BIT;
}
void Update()
{
uint32 mask = ((mTicks++ & RATE) - 1) >> 31;
((GPIO_TypeDef *)PORT)->BSRR = mSetReset & mask;
mSetReset ^= ((1 << BIT) | (1 << (BIT + 16))) & mask;
}
};
LedToggle<(uint32)GPIOC, 13, 1023> led;
它很丑陋,但它确实有效。我很想知道是否有人可以改进它?
最佳答案
声明bar<(foo*)0x80103400> myFoo;
格式错误,因为非类型模板参数必须是常量表达式,来自 [temp.arg.nontype]:
A template-argument for a non-type template-parameter shall be a converted constant expression (5.20) of the type of the template-parameter.
你传递的参数不是来自[expr.const]:
A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
— [...]
— areinterpret_cast
(5.2.10);
— [...]
声明bar<(foo*)0> huh
有效,因为它不涉及转换,它只是一个类型为 foo*
的空指针( 0
是特殊的)因此它是一个有效的常量表达式。
您可以改为简单地将地址作为模板非类型参数传递:
template <uintptr_t address>
struct bar { ... };
bar<0x8013400> myFooWorks;
这是可行的。
关于c++ - 使用绝对指针地址作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37303968/