使用枚举作为模板参数 [英] Using an enumeration as a template parameter

查看:175
本文介绍了使用枚举作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use a template class to provide some common functionality to some child classes that are very similar. The only variation is the enumeration that each uses.

这是父类

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;
}

这是其中一个孩子

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

class E_TableEvent : public E_EnumerationBase<enum TableEventEnum>
{
public:
    E_TableEvent();
};

这是构造函数

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

链接器抛出此错误:

e_tableevent.cpp:6: error: undefined reference to `E_EnumerationBase<TableEventEnum>::E_EnumerationBase()'

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

Can an enumeration be used as the parameter to a template like this?

推荐答案

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

Enumerations can be template parameters in exactly the same way that ints can.

enum Enum { ALPHA, BETA };

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

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

class Bar : public Foo <BETA> {
    // OK
}

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

这不是模板或继承的问题。这和你写的一样:

This isn't a problem with templates or inheritence. It's the same as if you written this:

struct Foo {
    Foo ();
}
int main () {
    Foo foo;
}

这篇关于使用枚举作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆