具有变量Number of Arguments的std::函数的矢量

Vector of std::function with variable Number of Arguments

本文关键字:std 函数 Arguments 变量 Number of      更新时间:2023-10-16

我想将event_handler存储到std::vector中,然后将std::vector存储到map中。根据映射键,我将使用不同的参数调用listeners[index].handler_(args...)

我意识到以上是不可能的,因为std::vector不能存储不同的类型;但我想知道我是否还有其他选择。

template<class... Args>
using Handler = std::function<void(Args &&... args)>;
template<typename T>
struct event_handler  {
event_handler(Handler<T> handler, bool once) : handler_(std::move(handler)), once_(once) {}
Handler<T> handler_;
bool once_;
};
std::vector<event_handler> listeners; // I known this line is wrong, here is just for example

您必须将要传递给事件处理函数的值与event_handler(可能为none/zero(和event_handler的应用程序/用户想要传递的值分开。

前者在std::function类型中定义为参数,当然,对于所有函数,此参数列表必须相同
当使用std::bind()将函数传递给事件处理程序时,后者将绑定到函数调用。

请注意,此解决方案承担的风险是,库的用户将指针或引用绑定到执行处理程序时不再存在的变量/对象。