问题描述
我正在尝试学习可变参数模板和函数.我不明白为什么这段代码不能编译:
I am trying to learn variadic templates and functions. I can't understand 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;
}
当我编译它失败并出现错误:
When I compile it fails with the error:
错误 C3520:'args':必须在此上下文中扩展参数包
(在函数 foo2
中).
推荐答案
可能发生包扩展的地方之一是在 braced-init-list 内.您可以通过将扩展放在虚拟数组的初始化列表中来利用这一点:
One of the places where a pack expansion can occur is inside a braced-init-list. You can take advantage of this by putting the expansion inside the initializer list of a dummy array:
template<typename... Args>
static void foo2(Args &&... args)
{
int dummy[] = { 0, ( (void) bar(std::forward<Args>(args)), 0) ... };
}
更详细地解释初始化器的内容:
To explain the content of the initializer in more detail:
{ 0, ( (void) bar(std::forward<Args>(args)), 0) ... };
| | | | |
| | | | --- pack expand the whole thing
| | | |
| | --perfect forwarding --- comma operator
| |
| -- cast to void to ensure that regardless of bar()'s return type
| the built-in comma operator is used rather than an overloaded one
|
---ensure that the array has at least one element so that we don't try to make an
illegal 0-length array when args is empty
演示.
在 {}
中扩展的一个重要优势是它保证了从左到右的评估.
An important advantage of expanding in {}
is that it guarantees left-to-right evaluation.
使用 C++17 折叠表达式,你可以直接写>
With C++17 fold expressions, you can just write
((void) bar(std::forward<Args>(args)), ...);
这篇关于可变模板包扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!