可变模板包扩展

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)), ...);

这篇关于可变模板包扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)