简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM