【问题标题】:std::function with lambda error for SDL event callbacks用于 SDL 事件回调的带有 lambda 错误的 std::function
【发布时间】:2017-04-01 02:23:18
【问题描述】:

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

我在事件轮询中调用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);
}

【问题讨论】:

    标签: c++ lambda sdl eventhandler std-function


    【解决方案1】:

    犯了一个非常愚蠢的错误...参数不匹配。正确的代码如下。 IE。我在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      相关资源
      最近更新 更多