c++variadic-templatesc++20fold-expression

use template fold expressions instead of recursive instantions of a function template?


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?


Solution

  • It could be:

    template<size_t ... Indices, typename... Ts>
    void bar2(std::index_sequence<Indices...>, Ts&&... ts) {
        auto action = [](size_t idx, auto&& arg) { std::cout << "item " << idx << "=" << arg << std::endl; };
        (action(Indices,std::forward<Ts>(ts)),...);
    }
    
    template<typename... Ts>
    void bar2(Ts&&... ts) {
        bar2(std::make_index_sequence<sizeof...(Ts)>(), std::forward<Ts>(ts)...);
    }
    

    Demo