2014-09-21 92 views
-1

我不明白爲什麼我不能定義這個結構:C++定義結構與模板

//Class.h 

template <class T> 
struct Callback { 
    T* Object; 
    std::function<void()> Function; 
}; 

template <class T> 
struct KeyCodeStruct { 
    typedef std::unordered_map<SDL_Keycode, Callback<T>> KeyCode; 
}; 

template <class T> 
struct BindingStruct{ 
    typedef std::unordered_map<int, KeyCodeStruct<T>> Binding; 
}; 


class Class { 
public: 
    template <class T> 
    void bindInput(SDL_EventType eventType, SDL_Keycode key, Callback<T> f); 
private: 
    template <class T> 
    BindingStruct<T> inputBindings; //How do I define this? This gives me an error. 
} 

它給人的錯誤: Member 'inputBindings' declared as a template. 我不知道模板非常好,所以我可能只是錯過我需要的信息。

更新(針對deviantfan)

現在我的CPP類運行到一個函數我有問題。

template <class T> 
void InputManager::bindInput(SDL_EventType eventType, SDL_Keycode key, Callback<T> f) 
{ 
    inputBindings[eventType][key] = f; 
} 

它說預期的類或命名空間。

回答

6

錯誤:

class Class { 
private: 
    template <class T> 
    BindingStruct<T> inputBindings; 
} 

右:

template <class T> 
class Class { 
private: 
    BindingStruct<T> inputBindings; 
} 
+0

請張貼完整的錯誤消息,並且在哪一行它發生。 – deviantfan 2014-09-21 23:13:34

+1

@TrevorPeyton看起來完全不同的問題。 – juanchopanza 2014-09-21 23:14:06

+0

@juanchopanza我試圖保持源代碼的最低限度。我不認爲這些會受到他的職位的影響。 – TrevorPeyton 2014-09-21 23:16:35

4

在回答您的更新

如果要定義你的類爲類模板,像這樣:

template <class T> 
class InputManager 
{ 
    ... 
}; 

然後在你的def從頭你需要證明你的InputManager與類型T一個實例:

template <class T> 
void InputManager<T>::bindInput(SDL_EventType eventType, SDL_Keycode key, Callback<T> f) 
{ 
    inputBindings[eventType][key] = f; 
} 

即:注意InputManager<T>而不僅僅是InputManager

+0

好吧,我假設我現在必須爲每個InputManager的方法添加一個模板?另外,在我使用InputManager的地方,我應該把類作爲什麼? InputManager ?它的工作原理似乎過於複雜,只是將模板放在單個結構上。 – TrevorPeyton 2014-09-21 23:19:10

+1

那你想要什麼?如果你確實需要一個模板類,你可以在使用時指定類型。如果你認爲這更復雜(因爲類型應該是「類」),那麼爲什麼模板? – deviantfan 2014-09-21 23:23:51

+1

@TrevorPeyton這就是模板的工作原理。你所遇到的問題是'Class'不是一個具體的類型 - 它是一個*類模板* - 它不會成爲一個具體的類型,除非你用一個模板參數實例化它,例如:'Class ';因此您需要使用此具體類型實例化'InputManager'類模板;所以它變成'InputManager >' – 2014-09-22 00:25:26