簡體   English   中英

使用枚舉作為模板參數

[英]Using an enumeration as a template parameter

我想使用模板類為一些非常相似的子類提供一些常用功能。 唯一的變化是每個使用的枚舉。

這是父類

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()'

枚舉可以用作這樣的模板的參數嗎?

枚舉可以是模板參數,與int可以完全相同。

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()的定義

這不是模板或繼承的問題。 就像你寫這個一樣:

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

語法用於值參數,就像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

僅供參考,因為您似乎使用Qt:只需看看Q_ENUMQMetaEnumQMetaEnum::fromType 這些可能很方便初始化你的字典。

您無法將模板功能的定義移動到單獨的源文件中。

在那里它根本不會被編譯,因為模板不能被編譯 ,只有模板實例可以。

您的單獨文件中的代碼未被編譯,這就是為什么您實際上沒有E_EnumerationBase<TableEventEnum>::E_EnumerationBase() 這就是你得到鏈接器錯誤的原因。

只需將所有模板代碼移動到標題中即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM