通过可变参数模板函数的参数包以相反的顺序迭代

Iterate in reverse order through the parameter-pack of a variadic template function

我正在尝试以相反的顺序迭代可变参数模板函数的参数包。我的想法是使用尾递归和一个专门的“空”模板函数来停止递归:

#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