[英]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)?如何在不手动列出所有三个参数(使其更具动态性)的情况下完成上述FooFunction
? Since there might be more parameters bar4
, bar5
etc. So just manually listing them won't work.由于可能有更多参数bar4
、 bar5
等。因此仅手动列出它们是行不通的。
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);
因此,如果我们采用专业化Test<B1, B2, B3>
,它有一个像explicit Test(B1 b1, B2 b2, B3 b3);
这样的构造函数explicit Test(B1 b1, B2 b2, B3 b3);
except that the names b1
, b2
, and b3
are just made up for explanation.除了名称b1
、 b2
和b3
只是为了解释而组成的。 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.最后一个将模板参数包BarType
和函数参数包bars
扩展到一起,匹配相应的包元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.