std::function & std::forward with variadic模板



最近我读到了关于可变模板的文章,基于我在网上看到的一个例子,我试图实现一个基本的事件系统。到目前为止,它似乎运行良好,但我试图更进一步,允许将N个参数传递给事件处理程序函数/回调,不幸的是,我收到的构建错误如下,我不确定我做错了什么。我研究了类似的源代码,但仍然无法弄清楚问题出在哪里。

D:Developmentlabc-cppEventEmitter3srcmain.cpp:30:68: error: parameter packs not expanded with '...':
return std::any_cast<std::function<R(Args)>>(eventCallback)(std::forward<Args>(args)...);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:Developmentlabc-cppEventEmitter3srcmain.cpp:30:68: note:         'Args'
Build finished with error(s).

到目前为止,如果删除...,则事件系统对于main中的2个已注册事件运行良好。

#include <any>
#include <string>
#include <iostream>
#include <functional>
#include <unordered_map>
class EventEmitter
{
private:
std::unordered_map<std::string, std::any> events;
public:
EventEmitter() {}
void on(const std::string &eventName, const std::any &eventCallback)
{
events[eventName] = eventCallback;
}
template <typename R>
R emit(const std::string &eventName)
{
const std::any &eventCallback = events[eventName];
return std::any_cast<std::function<R(void)>>(eventCallback)();
}
template <typename R, typename... Args>
R emit(const std::string &eventName, Args &&...args)
{
const std::any &eventCallback = events[eventName];
return std::any_cast<std::function<R(Args)>>(eventCallback)(std::forward<Args>(args)...);
}
virtual ~EventEmitter() {}
};
int fun1()
{
std::cout << "fun1" << std::endl;
return 1;
}
double fun2(int i)
{
std::cout << "fun2" << std::endl;
return double(i);
}
double fun3(int x, int y)
{
std::cout << "fun3" << std::endl;
return double(x + y);
}
int main(int argc, char *argv[])
{
EventEmitter e;
e.on("fun1", std::function<int(void)>(fun1));
e.on("fun2", std::function<double(int)>(fun2));

e.emit<int>("fun1");
e.emit<double, int>("fun2", 1);

// Variadic would have been handy right here I guess?
// e.on("fun3", std::function<double(int, int)>(fun3)); 
// e.emit<double, int>("fun3", 1, 2); 
return 0;
}

我该怎么解决这个问题?

好吧,你需要扩展它。

return std::any_cast<std::function<R(Args...)>>(eventCallback)(std::forward<Args>(args)...);
^^^^^^^

最新更新