是的,这是可能的:
// we need a compile-time helper to generate indices
template< std::size_t... Ns >
struct indices
{
typedef indices< Ns..., sizeof...( Ns ) > next;
};
template< std::size_t N >
struct make_indices
{
typedef typename make_indices< N - 1 >::type::next type;
};
template<>
struct make_indices< 0 >
{
typedef indices<> type;
};
有了这些助手,您就需要一个转发器来实现您的功能,如下所示:
template<typename R, typename... Args, std::size_t... Ns>
R myFunctionImpl(void *Data, void *function, indices<Ns...> ) {
auto f = (R (*)(Args...))function;
return f(read<Args>(Data, Ns + 1)...);// +1 because indices is zero-based
}
template<typename R, typename... Args>
R myFunction(void *Data, void *function) {
return myFunctionImpl< R, Args... >( Data, function, typename make_indices<sizeof...(Args)>::type() );
}
EDIT:它是如何工作的?首先,我们确定尺寸论证包 Args
通过sizeof.... make_indices<N>::type
然后扩展到indices<0,1,2,...,N-1>
。它作为实现函数的附加参数给出(来自刚刚创建虚拟实例的转发器),因此参数推导在实现函数一侧启动,并将生成的索引放入参数包中Ns
.
实现函数现在有两个大小相同的参数包,即Args
and Ns
。当通过省略号展开时...
,省略号展开整个表达它适用于并并行扩展所有参数包!在上面的例子中,表达式是read<Args>(Data, Ns+1)
,它很好地扩展为 OP 伪代码。