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
/break
s in your loop, here are some workarounds:
- Demo using try/throw. Note that
throw
s can cause tremendous slow down of this function; so only use this option if speed isn’t important, or thebreak
/return
s are genuinely exceptional. - Demo using variable/if switches.
These latter answers are honestly a code smell, but shows it’s general-purpose.