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)), ...);
这篇关于可变模板包扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可变模板包扩展
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01