SD57
SD57

Reputation: 83

Call function with number of parameters defined by template parameter value

I need to do:

#include <utility>
double& f(int i); // gets reference to an element in an array to be modified
void g(double& a); // uses references to modify the arguments
void g(double& a, double& b);
// other functions g with different amount of double& parameters

template<int N> void callG()
{
// should call g with N parameters: g(f(0), f(1),      , f(n));
}

int main()
{
  callG<1>; // calls g(f(0));
  callG<2>; // calls g(f(0), f(1));
  return 0;
}

I tried g(f(std::make_index_sequence<N>)...);

and some similar variants, but get

expected '(' for function-style cast or type construction

How do I make a parameter pack from an integer_sequence? Is there another solution?

Upvotes: 0

Views: 46

Answers (2)

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

You can only use the ... pack expansion operator when you have a pack. std::make_index_sequence<N> is not a pack. Add a layer of indirection:

template <std::size_t... Is>
void callGImpl(std::index_sequence<Is...>)
{
    g(f(Is)...);
}

template<int N> 
void callG()
{
    callGImpl(std::make_index_sequence<N>{});
}

live example on wandbox.org

Upvotes: 2

krisz
krisz

Reputation: 2695

#include <utility>

double& f(int i);
void g(double& a);
void g(double& a, double& b);

template <size_t... Ints>
void callG(std::integer_sequence<size_t, Ints...>) {
    g(f(Ints)...);
}

template <int N>
void callG() {
    callG(std::make_index_sequence<N>());
}

int main() {
    callG<1>();
    callG<2>();
    return 0;
}

Upvotes: 1

Related Questions