c++ - 如何将枚举类声明为模板类的内部类?

标签 c++ templates template-specialization forward-declaration enum-class

我正在抽象多个微 Controller 上的中断 vector 表。
我正在使用以下形式的模板类
(InterruptVectorTable.hpp(定义,包含在实现中))

template<class Device, class ResultType>
InterruptVectorTable
{
    enum class IRQType : ResultType;

}
Device是一种虚拟类,用于专门化模板。
class DeviceAtMega328p 
{
      public:
        static const int s_NumInterruptVectors = {26};
};

(这里我仍在考虑是否将26作为模板参数或以这种形式传递。)

由于每个微 Controller 都有自己的中断类型和值,应在编译时进行检查(由于枚举类),因此我还要专门介绍这种形式的特定中断(InterruptVectorTable.hpp(Implementation):
template<>
InterruptVectorTable< DeviceAtMega328p, uint8_t>
{
    enum class IRQType : ResultType
    {
        //RESET_IRQn = 0,               // Not available.
        INT0_IRQn = 1,
        INT1_IRQn = 2,
        PCINT0_IRQn = 3,
        PCINT1_IRQn = 4,
        PCINT2_IRQn = 5,
        WDT_IRQn = 6, 
        // .....
    };
}


这种方法似乎无法按预期方式工作(当前有太多错误无法指定,而明确指出了这一部分)。

最佳答案

首先,这不是您引入新模板类的方式:

// Wrong!
template<>
InterruptVectorTable<class Device, class ResultType>
{
    // ...
}

正确的方法:
template<class Device, class ResultType>
class InterruptVectorTable
{
    // ...
};

其次,您不能在模板专业中必须定义的模板中“向前声明”某些内容。专门知识一无所知,并且与“基本案例”毫无共同之处。

您只需执行以下操作即可使用您的代码:
template<>
class InterruptVectorTable<DeviceAtMega328p, uint8_t>
{
    enum class IRQType : uint8_t
    {
        //RESET_IRQn = 0,               // Not available.
        INT0_IRQn = 1,
        INT1_IRQn = 2,
        PCINT0_IRQn = 3,
        PCINT1_IRQn = 4,
        PCINT2_IRQn = 5,
        WDT_IRQn = 6, 
        //...........
    };
};
InterruptVectorTable的用户将简单地假设每个专业都定义了enum class IRQType。没有直接的方法强制特化这样做。对于IRQTypeResultType作为底层类型的要求,情况与此相同。

关于c++ - 如何将枚举类声明为模板类的内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669178/

相关文章:

c++ - "unresolved external symbol"关于 char 数组的模板特化

c++ - 依赖非类型模板参数和可变参数模板

c++ - 如果我的模板特化没有被执行,为什么它会被编译?

c# - 如何在 C# 中编码(marshal)指向一系列以 null 结尾的字符串的指针?

c++ - 如何编写适用于任何类型集合对象的 size() 函数?

c++ - 具有包扩展的可变参数函数模板不在最后一个参数中

c++ - 当它被称为 shared_ptr<Basic> 时调用派生类方法

python - 在 Django 应用程序中提供静态网页的最佳方式是什么?

C++ 返回数组语法

c++ - C++中lambda函数的继承参数