std::函数,带有 SDL 事件回调的 lambda 错误

std::function with lambda error for SDL event callbacks

本文关键字:回调 错误 事件 lambda SDL 函数 带有 std      更新时间:2023-10-16

我只想将lambda函数传递给函数进行回调。我正在使用std::function进行回调。我需要将数据传递给这个函数,这就是我遇到问题的地方。下面的代码错误说"无法转换为预期类型"。目标是对具有 SDL 的事件使用回调。我不确定这是否是正确的方法。我将回调函数存储在一个unordered_map中,键是SDL_Event.typestd::function vector

我在事件轮询中调用dispatch(),并在设置中调用subscribe。错误发生在subscribe() lambda 的[]

// main.cpp
window->subscribe(SDL_KEYDOWN, [](SDL_Event& ev) -> void {
    std::cout << "key pressed" << std::endl;
});
// eventhandler.cpp
void EventHandler::subscribe(int _event, std::function<void(const SDL_Event&)> _callback)
{
    m_callbacks[_event].push_back(_callback);
}
犯了

非常愚蠢的错误...参数不匹配。正确的代码如下。即我没有 lambda 中的const...

window->subscribe(SDL_KEYDOWN, [](const SDL_Event& ev) -> void {
    std::cout << "key pressed" << std::endl;
});
void EventHandler::subscribe(int _event, std::function<void(const SDL_Event&)> _callback)
{
    m_callbacks[_event].push_back(_callback);
}