这个可变模板是如何工作的

How does this variadic template work?

本文关键字:何工作 工作      更新时间:2023-10-16

我在看这个SO问题,不明白答案是怎么回事。我将在其中一个答案中张贴一份代码副本供参考:

template<int ...> struct seq {};
// How does this line work?
template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};
template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
double foo(int x, float y, double z)
{
    return x + y + z;
}
template <typename ...Args>
struct save_it_for_later
{
  std::tuple<Args...> params;
  double (*func)(Args...);
  double delayed_dispatch()
  {
     return callFunc(typename gens<sizeof...(Args)>::type());
  }
  template<int ...S>
  double callFunc(seq<S...>)
  {
     return func(std::get<S>(params) ...);
  }
};
int main(void)
{
  std::tuple<int, float, double> t = std::make_tuple(1, 1.2, 5);
  save_it_for_later<int,float, double> saved = {t, foo};
  cout << saved.delayed_dispatch() << endl;
}

我不明白的部分是:

template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};

return callFunc(typename gens<sizeof...(Args)>::type());的例子中,我假设sizeof..(Args)将是3。所以,

template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};

成为

template<3, {}> struct gens : gens<3-1, 3-1, {}> {};

这是正确的吗?如果是,接下来会发生什么?

让我们手动写下递归:

gens<3> : gens<2, 2>
gens<3> : gens<2, 2> : gens<1, 1, 2>
gens<3> : gens<2, 2> : gens<1, 1, 2> : gens<0, 0, 1, 2>

由于0:的部分专用化,递归停止

struct gens<0, S...>{ typedef seq<S...> type; }; 
// first 0 consumed by the partial specialization
// S = 0,1,2
struct gens<0, 0, 1, 2> { 
    typedef seq<0, 1, 2> type;
}