微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

#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;
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。