繁体   English   中英

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

[英]Variadic templates: iterate over type/template argument

我最近一直在使用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 */);
}

如果无法实现,是否有可用的解决方法或解决方案?

您不希望迭代类型,您想要创建参数包并在可变参数模板中展开它。 你有一个数组,所以你想要的包是一组整数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创建一个表示arg位置的整数的index_tuple ,并调度到另一个函数,该函数推导出整数并将包扩展为一个转换表达式列表,用作包装函数的参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM