c++ - 使用绝对指针地址作为模板参数

标签 c++ templates pointers

我有一个模板类,它的第一个模板参数是一个 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:
— [...]
— a reinterpret_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/

相关文章:

c++ - 尝试使用未知类型的模板非类型参数

c++ - Qt : Accessing Secure Objects using session-id from a server

c++ - 从 C++ (gcc) 连接到 PostgreSQL

c++ - pugixml 包含目录设置为未从 pugixml 配置 cmake 文件中找到

c - 下面如何进行多维数组的指针运算?

c - 简单注册测试失败

C函数指针翻译成Delphi/Pascal?

c++ - 为轴添加 slider 时未定义对 main 的引用

c++ - 不使用尖括号的模板 - 重载?

C++模板题