[英]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.