以相反的顺序遍历可变模板函数的参数包



我正试图以相反的顺序迭代一个可变模板函数的参数包。我的想法是使用尾部递归;"空";模板函数停止递归:

#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, 4, 5}]’
p.cc:30:12:   required from ‘void f() [with int H = 1; int ...T = {2, 3, 4, 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;
}

我们开始:https://ideone.com/TZal7p

最新更新