Wu Zhenwei
Wu Zhenwei

Reputation: 518

Expand a parameter pack with a counter

I want to expand a paramter pack into a function call, like this:

func(get_value(arg)...);

where func and get_value are two functions. The question is that get_value is sensitive to evaluation order, so I think one solution is to generate something like this:

func(get_value(arg0, 0), get_value(arg1, 1), get_value(arg2, 2));

if, for example, there're three parameters. With this counter I'll know the evaluation order. This there a way to do so?

Or as another solution, is there a way to simply specify the evaluation order of those calls to get_value with args? (If so, I don't even need a counter.)

Upvotes: 3

Views: 1418

Answers (1)

Pradhan
Pradhan

Reputation: 16737

You can "zip" parameter packs together. So, something like this, using the definition of seq from here:

template <typename ... Args, int ... N>
void F(Args... args, seq<N...>)
{
func(get_value(args, N)...);
}

template <typename ... Args>
void FHelper(Args&&... args)
{
 F(std::forward<Args>(args)..., typename gens<sizeof...(Args)>::type ());
}

and you would call FHelper.

A simpler solution, in the case of get_value having a fixed return type would be to change func to take an initializer_list as input and call it like this :

func({get_value(args)...});

This preserves call order since the commas in the initializer-list are sequence points.

Upvotes: 4

Related Questions