首页 > 解决方案 > 如何将 lambda/std::function/Functor 传递给可变参数函数

问题描述

我有一个像这样的可变参数函数:

template <class... PickComponents, size_t... PickComponentIndices>
void iterateEntitiesInternal(
  const std::function<void(Entity, const PickComponents &...)> &iterFn,
  std::index_sequence<PickComponentIndices...> sequence
);

template <class... PickComponents>
void iterateEntities(const std::function<void(Entity, const PickComponents &...)> &iterFn) {
  iterateEntitiesInternal(iterFn, std::index_sequence_for<PickComponents...>{});
}

我希望能够像这样调用函数:

iterateEntities<A, B, C>([](Entity entity, const auto &c1, const auto &c2, const auto &c3) {
  // ...
});

有没有办法让这个工作?我尝试创建一个模板结构,如:

template <typename T> struct IterFnType { typedef T type; };

并像这样使用它:

template <class... PickComponents>
void iterateEntities(const typename IterFnType<std::function<void(Entity, const PickComponents &...)>>::type &iterFn);

但它在 GCC 中给了我一个编译器错误:

错误:'typename liquid::EntityStorageSparseSet::IterFnType' 名称 'template<class ... ComponentTypes> template structliquid::EntityStorageSparseSet::IterFnType',它不是一个类型

将 lambdas 传递给可变参数函数的正确方法是什么?

标签: c++lambdavariadic-templates

解决方案


推荐阅读