参数包未用'...'扩展 [英] Parameter packs not expanded with '...'

查看:110
本文介绍了参数包未用'...'扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#include <iostream>
using namespace std;

int print(int i)
{
    cout << endl << i;
}

template<typename ...Args>
inline void pass(Args&&...args)
{

}

template<typename ...args>
inline void expand(args&&... a)
{
    print(a) ...; //this doesn't expand
    //pass( print(a)... ); this works
}

int main() {
    expand(1,2,3,4);
    return 0;
}

抛出错误:

 In function 'void expand(args&& ...)':
error: expected ';' before '...' token
  print(a) ...;
           ^
parameter packs not expanded with '...':
  print(a) ...;
              ^

为什么使用 pass()函数是否必需?

Why is the use of the pass() function necessary?

推荐答案

本质上是扩展参数包 E ... 生成一个列表 E1,E2,[...],EN ,一个 E 用于包中的每个元素。这种语法结构仅在语法正确的列表中有效,例如在函数调用,初始化列表等中。包含多个逗号运算符的表达式不计算在内。

Essentially, expanding a parameter pack E... produces a list E1, E2, [...], EN, one E for each element in the pack. This syntactic construct is only valid in places where lists are grammatically correct, such as in function calls, initializer lists etc. An expression containing multiple comma operators does not count.

I相信使用折叠表达式 N4295:折叠表达式(Andrew Sutton,Richard Smith)),您可以简单地编写:

I believe that with fold expressions (N4295: Folding expressions (Andrew Sutton, Richard Smith)) you'll be able to simply write:

(print(a), ...);

在此表达式中,


  • print(a)是带有未扩展参数包的表达式,

  • 是运算符,

  • ... 指定正确的倍数扩展。

  • print(a) is an expression with an unexpanded parameter pack,
  • , is the operator and
  • ... designates the right fold expansion.

整个表达式的结果是(print(a),...)将被转换为

The result of the entire expression is that (print(a), ...) will be transformed into

print(a1) , (print(a2), (print(a3), print(a4))) // (assuming four elements). 

这篇关于参数包未用'...'扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆