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)), ...);
这篇关于可变模板包扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可变模板包扩展
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
