Given a variadic parameter pack, I would like to call a function with each element and its index in the pack.
I have a simple example below which uses recursive instantiations of a function template to achieve this. (on godbolt)
#include <iostream>
#include <tuple>
template<std::size_t I, typename Tuple>
void foo(Tuple&& tuple)
{
std::cout << "item " << I << "=" << std::get<I>(tuple) << '\n';
if constexpr (I + 1 < std::tuple_size_v<std::decay_t<Tuple>>)
foo<I+1>(tuple);
}
template<typename... Ts>
void bar(Ts... ts)
{
foo<0>(std::tuple(ts...));
}
int main()
{
bar(5, 3.14, "hello world", 'c');
return 0;
}
This works as expected:
item 0=5 item 1=3.14 item 2=hello world item 3=c
Is it possible to achieve the same result using std::index_sequence
and a template fold expression?
It could be:
Demo