使用枚举作为模板参数

Isl*_*Cow 22 c++ inheritance templates

我想使用模板类为一些非常相似的子类提供一些常用功能.唯一的变化是每个使用的枚举.

这是父类

template<typename T> class E_EnumerationBase : public SimpleElement
{
public:
    E_EnumerationBase();
    virtual bool setValue(QString choice);
    virtual T getState();

protected:
    T state;
    QHash<QString, T> dictionary;
};

template<typename T> E_EnumerationBase<T>::E_EnumerationBase() {
    state = 0;
}

template<typename T> bool E_EnumerationBase<T>::setValue(QString choice) {
    T temp;
    temp = dictionary.value(choice, 0);
    if (temp == 0) {
        return false;
    }

    value = choice;
    state = temp;
    return true;
}

template<typename T> T E_EnumerationBase<T>::getState() {
    return state;
}
Run Code Online (Sandbox Code Playgroud)

这是其中一个孩子

enum TableEventEnum {
    NO_VALUE = 0,
    ATTRACT = 1,
    OPEN = 2,
    CLOSED = 3
};

class E_TableEvent : public E_EnumerationBase<enum TableEventEnum>
{
public:
    E_TableEvent();
};
Run Code Online (Sandbox Code Playgroud)

这是构造函数

E_TableEvent::E_TableEvent()
{
    state = NO_VALUE;
    dictionary.insert("attract", ATTRACT);
    dictionary.insert("open", OPEN);
    dictionary.insert("closed", CLOSED);
}
Run Code Online (Sandbox Code Playgroud)

链接器抛出此错误:

e_tableevent.cpp:6: error: undefined reference to `E_EnumerationBase<TableEventEnum>::E_EnumerationBase()'
Run Code Online (Sandbox Code Playgroud)

枚举可以用作这样的模板的参数吗?

spr*_*aff 35

枚举可以是模板参数,与int可以完全相同.

enum Enum { ALPHA, BETA };

template <Enum E> class Foo {
    // ...
};

template <> void Foo <ALPHA> :: foo () {
    // specialise
}

class Bar : public Foo <BETA> {
    // OK
}
Run Code Online (Sandbox Code Playgroud)

但你根本没有提供定义 E_EnumerationBase::E_EnumerationBase()

这不是模板或继承的问题.就像你写这个一样:

struct Foo {
    Foo ();
}
int main () {
    Foo foo;
}
Run Code Online (Sandbox Code Playgroud)

  • 现在 (C++11) 也可以使用 `enum class` 吗? (3认同)

Seb*_*ach 8

语法用于值参数,就像typename参数一样.基本上,你只需要替换你typename的名字enum:

enum Foo { Bar, Frob };

template <Foo F> struct Boom {};  // primary template
template <> struct Boom<Bar> {};  // specialization of whole class

...

template <> void Boom<Frob>::somefun() {}  // specialization of single member
Run Code Online (Sandbox Code Playgroud)

  • 您是否建议将枚举用于其值而不是用作类型?首先,我试图限制哈希表中的值。 (2认同)
  • “除非你认真理解模板,否则不要编写严肃的模板代码”——这有点傲慢。鼓励反馈会更有帮助。 (2认同)