简体   繁体   中英

How to pass in variadic list of parameters to a function that takes in variable parameters?

I have a template parameter pack that I would like to pass into a function that takes in a variable number of parameters. Since I don't know how many parameters I actually have, how can I pass in an unknown amount of parameters' data members into the function?

template <typename BarType...>
Class Test
{
   explicit Test(BarType ...bars)
   {
   // Calling this function with parameter pack instead of this way 
   // (which won't even work with above parameter pack)
   FooFunction(
   [](BarType &bar1){ return bar1.bar_member; },
   [](BarType &bar2){ return bar2.bar_member; },
   [](BarType &bar3){ return bar3.bar_member; })
   }

}

How can I accomplish the above FooFunction without manually listing out all three parameters (making it more dynamic)? Since there might be more parameters bar4 , bar5 etc. So just manually listing them won't work.

It looks like you might want:

template <typename BarType...>
Class Test
{
   explicit Test(BarType ...bars)
   {
       FooFunction(bars.bar_member ...);
   }
};

The most common way of using a parameter pack is to expand it, by putting a representation of what should be in each element of a list, followed by the ellipsis token ... .

So if we take the specialization Test<B1, B2, B3> , it has a constructor like explicit Test(B1 b1, B2 b2, B3 b3); except that the names b1 , b2 , and b3 are just made up for explanation. In that function body, some possible things involving pack expansions and what they would instantiate as:

std::make_tuple(bars...) -> std::make_tuple(b1, b2, b3)
std::tuple<BarType...>   -> std::tuple<B1, B2, B3>
f(g(bars) ...)           -> f(g(b1), g(b2), g(b3))
h<BarType>(bars)...      -> h<B1>(b1), h<B2>(b2), h<B3>(b3)

The last one expands both the template parameter pack BarType and the function parameter pack bars together, matching up the corresponding pack elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM