可变参数模板包扩展
在 Andrei 在 GoingNative 2012 上的演讲中,他谈到了 Variadic 模板,并且他在某一时刻通过下面的示例解释了参数包扩展的工作原理。作为这个主题的新手,我发现很难理解每种情况的工作原理,有人可以解释一下在 gun
的每个函数调用中扩展是如何工作的吗?
template<class... Ts> void fun(Ts... vs) {
gun(A<Ts...>::hun(vs)...);
gun(A<Ts...>::hun(vs...));
gun(A<Ts>::hun(vs)...);
}
In Andrei's talk on GoingNative 2012 he talks about Variadic Templates, and he explains at one point by way of the example underneath how the parameter pack expansions work. Being fairly new to this subject I found it fairly hard to follow how each case works, could anybody please explain how the expansion works in each function call of gun
?
template<class... Ts> void fun(Ts... vs) {
gun(A<Ts...>::hun(vs)...);
gun(A<Ts...>::hun(vs...));
gun(A<Ts>::hun(vs)...);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1.
2.
这应该是显而易见的。
3.
(在这种情况下,如果 Ts 和 vs 的长度不同,程序将无法编译)
...
将扩展其前面的模式(包括任何参数包),这意味着,在foo(Ts, Us, Vs)...
,列表中的每个成员Ts
、Us
、Vs
(在锁定步骤中枚举)将被替换为该模式,并且将形成一个逗号分隔的列表:如果存在嵌套扩展,则最里面的模式将首先扩展。因此,在情况 1 中,模式
Ts
将首先扩展为T1, T2, …, Tn
。然后,外部...
之前的模式是A::fun(vs)
— 请注意Ts< /code> 已扩展 - 因此它将扩展为
A::fun(v1), A::fun(v2), …, A::fun(vm)
通过替换v1
,v2
等进入vs
。1.
2.
This should be obvious.
3.
(In this case the program won't compile if the lengths of Ts and vs differ)
The
...
will expand a pattern (which includes any parameter packs) preceding it, meaning that, infoo(Ts, Us, Vs)...
, each member of the listTs
,Us
,Vs
(enumerated in lock step) will be substituted into that pattern, and a comma separated list will be formed:And if there are nested expansions, the innermost patterns will be expanded first. Therefore, in case 1, the pattern
Ts
will first be expanded intoT1, T2, …, Tn
. And then, the pattern preceding the outer...
isA<T1, T2, …, Tn>::fun(vs)
— note thatTs
has been expanded — so it will be expanded toA<T1, T2, …, Tn>::fun(v1), A<T1, T2, …, Tn>::fun(v2), …, A<T1, T2, …, Tn>::fun(vm)
by substitutingv1
,v2
, etc. intovs
.KennyTM 的回答很完美。我也喜欢样品。但由于他的答案很抽象,我不认为在他的答案中添加演示是正确的事情。所以他的答案的演示就在这里。我假设他的答案是正确的,我自己一无所知。 (如果你支持这个,也支持他)
显然这都是伪代码,只是显示扩展状态。
KennyTM's answer is perfect. I just also like samples. But since his answer is abstract, I didn't feel like adding demos to his answer is the correct thing. So demos for his answer are here. I'm assuming his answer is right, I know nothing myself. (If you upvote this, upvote his too)
Obviously this is all psudocode just showing the expanded states.