Variadic template pack expansion(可变模板包扩展)
问题描述
我正在尝试学习可变参数模板和函数.我不明白为什么这段代码不能编译:
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':必须在此上下文中扩展参数包
Error C3520: 'args': parameter pack must be expanded in this context
(在函数 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)), ...);
这篇关于可变模板包扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可变模板包扩展
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01