How can I iterate over a packed variadic template argument list?

If your inputs are all of the same type, see OMGtechy‘s great answer.

For mixed-types we can use fold expressions (introduced in c++17) with a callable (in this case, a lambda):

#include <iostream>

template <class ... Ts>
void Foo (Ts && ... inputs)
{
    int i = 0;

    ([&]
    {
        // Do things in your "loop" lambda

        ++i;
        std::cout << "input " << i << " = " << inputs << std::endl;

    } (), ...);
}

int main ()
{
    Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}

Live demo

(Thanks to glades for pointing out in the comments that I didn’t need to explicitly pass inputs to the lambda. This made it a lot neater.)


If you need return/breaks in your loop, here are some workarounds:

  • Demo using try/throw. Note that throws can cause tremendous slow down of this function; so only use this option if speed isn’t important, or the break/returns are genuinely exceptional.
  • Demo using variable/if switches.

These latter answers are honestly a code smell, but shows it’s general-purpose.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)