Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 579
Wu Zhenwei Avatar asked Mar 19 '26 04:03

Wu Zhenwei


1 Answers

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.

like image 117
Pradhan Avatar answered Mar 20 '26 20:03

Pradhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!