Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

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

I'm trying to iterate in reverse order through the parameter-pack of a variadic template function. My idea was to use tail recursion and a specialized "empty" template function to stop the recursion:

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

However the code above does not compile:

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...>();

I feel this is just a syntax error -- but I'm unable to find the solution by myself. Any idea?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because you should provide, well, template declaration before specializations:

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

Here we go: https://ideone.com/TZal7p


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...