能否使用FastDelegate创建对参数包逐参数调用的委托(支持成员函数)
使用FastDelegate实现参数包逐个调用委托(支持成员函数)
完全可以用FastDelegate实现需求,替代你当前的lambda包装写法。FastDelegate本身支持绑定全局函数、成员函数,我们只需要封装一个通用的参数包遍历逻辑,配合FastDelegate的绑定能力就能实现目标。
实现方案
首先封装一个接受FastDelegate的遍历函数,负责展开参数包并逐个调用委托:
#include "FastDelegate.h" template<typename DelegateType, typename... Args> void ForEachWithFastDelegate(DelegateType delegate, Args&&... args) { // 静态断言确保传入的是FastDelegate类型 static_assert(fastdelegate::traits::is_delegate<DelegateType>::value, "必须传入FastDelegate类型"); // 展开参数包,对每个参数调用委托 (void)std::initializer_list<int>{(delegate(std::forward<Args>(args)), 0)...}; }
然后在你的类中直接绑定成员函数到FastDelegate,传入遍历函数即可:
class CNetworkMenu { private: void RemoveItemByAction(int action) { // 这里保留原有的删除逻辑 } public: template<typename... T> void RemoveItemsByActions(T... args) { // 绑定当前对象的成员函数到FastDelegate auto itemRemover = fastdelegate::MakeDelegate(this, &CNetworkMenu::RemoveItemByAction); // 遍历参数包,逐个调用委托 ForEachWithFastDelegate(itemRemover, std::forward<T>(args)...); } };
说明
- FastDelegate的
MakeDelegate函数可以直接绑定对象指针和成员函数,无需手动写lambda捕获上下文,代码更简洁。 - 遍历函数用
std::initializer_list来展开参数包,确保每个参数都被传入委托调用一次,和你原有的循环逻辑效果完全一致。 - 如果需要支持不同参数类型的委托,只需要调整FastDelegate的模板参数(比如
FastDelegate2对应两个参数的函数),遍历函数的模板会自动适配。
内容的提问来源于stack exchange,提问作者Adrián
相关产品推荐
相关产品推荐

