可变参数模板:迭代类型/模板参数
Variadic templates: iterate over type/template argument
我最近一直在使用 libffi,由于它使用 C API,任何抽象都是通过使用 void 指针(好的 ol' 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
,并调度到另一个函数,该函数推导整数并将包扩展为强制转换表达式列表,以用作包装函数的参数。
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型