einpoklum
einpoklum

Reputation: 131626

How do I convert a template parameter pack into multiple pointer arguments to a function?

I want to implement the following:

template <typename Functor, typename... Params>
void foo(
    size_t n
    /* magic goes here, producing function parameters p1, p2, etc. */
    /* corresponding to the parameter pack.                        */
)
{
    for(size_t i = 0; i < n; i ++) {
        std::cout << Functor()( 
            /* pass p1[i], p2[i], etc. corresponding to the  */
            /* parameter pack.                               */
        )  << '\n';
    }
}

thus foo would expand into something like:

void foo(
    size_t n,
    const int* __restrict__ p1,
    const int* __restrict__ p2
)
{
    for(size_t i = 0; i < n; i ++) {
        std::cout << std::plus()(p1[i], p2[i]) << '\n';
    }
}

I have a vague intuition that I might need to go beyond the standard library into something like Fusion, Brigand or Hana, which I've just started looking into; but - maybe I'm wrong and it's simpler than I think.

Note:

Upvotes: 3

Views: 1294

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275435

template<class Functor, class...Ts>
void foo( std::size_t n,
  Ts const* __restrict__ ... ts
) {
  for(size_t i = 0; i < n; i ++) {
    std::cout << Functor{}( ts[i]...)  << '\n';
  }
}

well, that was easy.

Live example.

Upvotes: 4

Related Questions