gpt4 book ai didi

C++ 从模板函数中存储数据?

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:52 24 4
gpt4 key购买 nike

我正在尝试将函数参数中的数据存储到 unordered_map 中,其中 unordered_map 存储在另一个 unordered_map 中。在第二个 unordered_map 中,元素是一个结构。这是它看起来像的简化版本:

//Callback.h

//Callback struct containing Object and Object function
struct CallbackStruct {
EXClass* object;
std::function<void()> function;
}

//Map with Keyboard keys as the key and CallbackStruct as the element
typedef std::unordered_map<Key, Callback> KeyCode;

//Map with an int as the key and KeyCode as the element
typedef std::unordered_map<int, KeyCode> BindingEvent;

class Callback {
public:
//This function takes the data and stores it
void bindKey(int Event, Key iKey, EXClass* classObj, std::function<void()> classFunction);
private:
//This is where the data is stored
BindingEvent handler;
}

//Callback.cpp

void Callback::bindKey(int Event, Key iKey, EXClass* classObj, std::function<void()> classFunction)
{
//This is where the function data is stored
CallbackStruct newCallback = { classObj, classFunction };
handler[Event][iKey] = newCallback;
}

现在效果很好,但问题来了

这只适用于 EXClass 类。我需要它为任何有权访问 Callback.h 的类工作

首先,我将 CallbackStruct 放在模板中。之后,我必须将所有 unordered_maps 设置为模板。这意味着当我定义 BindingEvent 处理程序 时,它需要一个模板,这意味着您不能在类中定义它(也许?)。

我曾尝试将回调类设置为模板,但这行不通,因为它只有初始化它的类的类。 Callback 的单个实例将在多个类之间共享,模板需要与每个类一起使用。

这是我尝试过的源代码:

//InputManager.h

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

template <class T>
struct KeyCodeStruct { //I have to place these in structs because templates are not allowed in typedefs
typedef std::unordered_map<SDL_Keycode, Callback<T>> KeyCode;
};

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

class InputManager {
public:
template <class T>
void bindInput(SDL_EventType eventType, SDL_Keycode key, Callback<T> f);
void updateInput(SDL_Event event);
private:
template <class T>
BindingStruct<T> bindingInput; //This is where the main issue is; Can't do this
};

最佳答案

终于明白了!虽然我仍然不确定是否可以在模板中使用数据结构,但我设法让我的回调系统正常工作。我只需要使用 std::function 和 std::bind。对于那些对这里的最终结果感兴趣的人,它是:

//InputManager.h

typedef std::function <void()> Callback;

typedef std::unordered_map<SDL_Keycode, Callback> KeyCode;

typedef std::unordered_map<int, KeyCode> Binding;


class InputManager {
public:
template <class T>
void bindInput(SDL_EventType eventType, SDL_Keycode key, T* newObj, void (T::*mf)())
{
inputBindings[eventType][key] = std::bind(mf, newObj);
};
void updateInput(SDL_Event event);
private:
Binding inputBindings;
};

...

//InputManager.cpp

void InputManager::updateInput(SDL_Event event)
{
while(SDL_PollEvent(&event)) {
if (inputBindings[event.type][event.key.keysym.sym])
inputBindings[event.type][event.key.keysym.sym]();
}
}

关于C++ 从模板函数中存储数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25981985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com