问题描述
我正在尝试通过可变参数模板函数的参数包以相反的顺序进行迭代。我的想法是使用尾递归和专门的“空”模板函数来停止递归:
#include <iostream>
template<>
void f() {}
template<int H,int... T>
void f()
{
f<T...>();
std::cout << H << std::endl;
}
int main()
{
f<1,2,3,4,5>();
return 0;
}
但是上面的代码不能编译:
p.cc:25:8: error: ‘f’ is not a template function
void f() {}
^
p.cc: In instantiation of ‘void f() [with int H = 5; int ...T = {}]’:
p.cc:30:12: recursively required from ‘void f() [with int H = 2; int ...T = {3,5}]’
p.cc:30:12: required from ‘void f() [with int H = 1; int ...T = {2,5}]’
p.cc:36:18: required from here
p.cc:30:12: error: no matching function for call to ‘f()’
f<T...>();
^
p.cc:28:6: note: candidate: template<int H,int ...T> void f()
void f()
^
p.cc:28:6: note: template argument deduction/substitution Failed:
p.cc:30:12: note: Couldn't deduce template parameter ‘H’
f<T...>();
我感觉这只是一个语法错误——但我自己无法找到解决方案。有什么想法吗?
解决方法
因为您应该在专业化之前提供模板声明:
#include <iostream>
template<typename...> void f();
template<>
void f() {}
template<int H,int... T>
void f()
{
f<T...>();
std::cout << H << std::endl;
}
int main()
{
f<1,2,3,42,5>();
return 0;
}