可变参数模板:迭代类型/模板参数

6

最近我一直在使用libffi,因为它使用C API,所以任何抽象都是通过使用void指针完成的(好老的C)。我正在创建一个类(使用可变模板),它利用这个API。类声明如下:(其中Ret=返回值,Args=函数参数)

template <typename Ret, typename... Args>
class Function

在这个类中,我还声明了两个不同的函数(简化版):

Ret Call(Args... args); // Calls the wrapped function
void CallbackBind(Ret * ret, void * args[]); // The libffi callback function (it's actually static...)

我希望能够从 CallbackBind 中使用 Call,这是我的问题。我不知道应该如何将 void* 数组转换为模板参数列表。大体上来说,这就是我想要的:

CallbackBind(Ret * ret, void * args[])
{
 // I want to somehow expand the array of void pointers and convert each
 // one of them to the corresponding template type/argument. The length
 // of the 'void*' vector equals sizeof...(Args) (variadic template argument count)

 // Cast each of one of the pointers to their original type
 *ret = Call(*((typeof(Args[0])*) args[0]), *((typeof(Args[1])*) args[1]), ... /* and so on */);
}

如果无法实现,是否有任何解决方法或其他不同的解决方案可用?

1
你为什么不能直接从回调函数中调用库的API呢?你已经有了一个void*,而且它已经期望这样做。 - Mark B
为什么要使用固定数量的参数调用可变参数模板函数呢?基于“args的长度等于sizeof...(Args)”这一事实,您已经知道所需的参数数量,为什么还要使用可变参数模板呢? - mfontanini
@MarkB 因为CallbackBind是从库的API中调用的,所以我正在尝试调用自己的函数,该函数不使用void指针。 @mfontanini 我想要一个类来模仿std::function,因此我需要可变参数模板(例如operator()(Args...))。 - Elliott Darfink
2
我很想写类似于 CallAux<Tuple, Indices...>::call(void * args[]) { Call(*static_cast<(*std::tuple_element<Tuple, Indices>*>(args[Indices]))...); } 这样的东西。 - Kerrek SB
1
你应该看一下这个:https://dev59.com/B2sz5IYBdhLWcg3wfn-6。你可以根据自己的需求进行调整 :D - mfontanini
1个回答

5

您不需要遍历类型,而是需要创建一个参数包并将其在可变模板中进行展开。由于您有一个数组,因此您想要的参数包是整数0、1、2...作为数组索引。

#include <redi/index_tuple.h>

template<typename Ret, typename... Args>
struct Function
{
  Ret (*wrapped_function)(Args...);

  template<unsigned... I>
  Ret dispatch(void* args[], redi::index_tuple<I...>)
  {
    return wrapped_function(*static_cast<Args*>(args[I])...);
  }

  void CallbackBind(Ret * ret, void * args[])
  {
    *ret = dispatch(args, to_index_tuple<Args...>());
  }
};

使用类似index_tuple.h的工具进行编码。

其中的技巧在于,CallbackBind创建了一个表示参数位置的整数的index_tuple,并分派给另一个函数,该函数推导整数并将打包扩展为类型转换表达式列表,作为封装函数的参数。


多么优雅的解决方案!对我来说完美无缺。 - Elliott Darfink

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接