可变参数模板、递归、非类型名参数

Variadic templates, recursion, non-typename parameters

我正在尝试使用非类型名称参数构建一些简单的可变参数模板:

  #include <iostream>

  void myf()
  {
  }

  template<int Arg1, int ... Args> void myf()
  {
     std::cout << Arg1 << ", ";
     myf<Args...>();
  }

  int main()
  {
     myf<1,2,3,4,5>();
  } 

尝试编译并得到:

test.cpp: In instantiation of ‘void myf() [with int Arg1 = 5; int ...Args = {}]’:
test.cpp:10:18:   recursively required from ‘void myf() [with int Arg1 = 2; int ...Args = {3, 4, 5}]’
test.cpp:10:18:   required from ‘void myf() [with int Arg1 = 1; int ...Args = {2, 3, 4, 5}]’
test.cpp:15:20:   required from here
test.cpp:10:18: error: no matching function for call to ‘myf()’
     myf<Args...>();
              ^
test.cpp:10:18: note: candidate is:
test.cpp:7:39: note: template<int Arg1, int ...Args> void myf()
     template<int Arg1, int ... Args> void myf()
                                   ^
test.cpp:7:39: note:   template argument deduction/substitution failed:
test.cpp:10:18: note:   couldn't deduce template parameter ‘Arg1’
     myf<Args...>();

看来,递归终止不起作用。终止非类型名可变参数模板递归的正确方法是什么?

正确的解决方案是将最后一个案例作为一个参数案例,而不是无参数案例。问题是您的最后一次通话扩展为:

myf<>();

这不是很有效。

相反,您可能想要这样做:

// one parameter case:
template<int Arg>
void myf()
{
    std::cout << Arg << std::endl;
}

// two or more parameters:
template<int Arg1, int Arg2, int... Args>
void myf()
{
   std::cout << Arg1 << ", " << Arg2 << ", ";
   myf<Args...>();
}

这是 Coliru

上的一个实例