2014-09-21 52 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