Home > OS >  use template fold expressions instead of recursive instantions of a function template?
use template fold expressions instead of recursive instantions of a function template?

Time:04-10

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?

CodePudding user response:

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

CodePudding user response:

No need to use std::index_sequence

#include <iostream>

template<typename... Ts>
void bar(Ts&&... ts) {
  std::size_t idx = 0;
  ((std::cout << "item " << idx   << "=" << ts << '\n'), ...);
}

Demo

If you want I to be a non-type template parameter, then a template lambda is enough

template<typename... Ts>
void bar(Ts&&... ts) {
  [&]<std::size_t... Is>(std::index_sequence<Is...>) {
    ((std::cout << "item " << Is << "=" << ts << '\n'), ...);
  }(std::index_sequence_for<Ts...>{});
}
  • Related