问题描述
我试图学习可变参数模板和函数。我不能undestand,为什么这个代码不编译:
I trying to learn variadic templates and functions. I can't undestand, why this code doesn't compile:
template<typename T> static void bar(T t) {} template<typename... Args> static void foo2(Args... args) { (bar(args)...); } int main() { foo2(1, 2, 3, "3"); return 0; }
编译失败,错误为:
参数包只能在函数 foo2 中扩展。
(in function foo2).
推荐答案
一个严格定义的上下文列表,而operator ,不是其中之一。换句话说,不可能使用包扩展来生成由一系列由运算符,定界的子表达式组成的表达式。
Parameter packs can only be expanded in a strictly-defined list of contexts, and operator , is not one of them. In other words, it's not possible to use pack expansion to generate an expression consisting of a series of subexpressions delimited by operator ,.
经验法则是扩展可以生成,分隔模式的列表, code>是一个列表分隔符。
The rule of thumb is "Expansion can generate a list of ,-separated patterns where , is a list delimiter." Operator , does not construct a list in the grammar sense.
要为每个参数调用一个函数,可以使用,使用递归(这是可变模板程序员框中的主要工具):
To call a function for each argument, you can use recursion (which is the primary tool in the variadic template programmer's box):
template <typename T> void bar(T t) {} void foo2() {} template <typename Car, typename... Cdr> void foo2(Car car, Cdr... cdr) { bar(car); foo2(cdr...); } int main() { foo2 (1, 2, 3, "3"); }
这篇关于Variadic模板包扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!