c++ - 在折叠表达式中扩展参数包作为 lambda 捕获的一部分 - gcc 与 clang

标签 c++ lambda language-lawyer variadic-templates c++17

考虑以下代码片段:

template <int... Is>
void foo()
{
    ([i = Is]{}(), ...); 
}
  • clang++ (trunk) 使用 -std=c++17

  • 成功编译代码
  • g++ (trunk) 编译失败,错误如下:

    <source>: In function 'void foo()':
    
    <source>:4:11: error: parameter packs not expanded with '...':
        ([i = Is]{}(), ...);
            ^~
    
    <source>:4:11: note:         'Is'
    <source>:4:16: error: operand of fold expression has no unexpanded parameter packs
        ([i = Is]{}(), ...);
        ~~~~~~~~~~^~
    

    on godbolt.org

这是一个 g++ 错误,还是标准阻止将参数包扩展为 lambda-introducer 的一部分?

最佳答案

这看起来像是一个错误。

[temp.variadic]/4

A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or more instantiations of the pattern in a list (described below). The form of the pattern depends on the context in which the expansion occurs. Pack expansions can occur in the following contexts:

  • ... [not relevant]
  • In a fold-expression; the pattern is the cast-expression that contains an unexpanded parameter pack.

带有函数调用的完整 lambda 表达式(如您所见)是有效的 cast-expression如果有人遵循语法产生式。没有理由将其排除在有效模式之外。

关于c++ - 在折叠表达式中扩展参数包作为 lambda 捕获的一部分 - gcc 与 clang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49722969/

相关文章:

c++ - 将 unsigned char* 转换为 std::string

使用 lambda 的 Python 闭包

c++ - C++20 中的 std::launder 用例

c++ - 为什么成员变量不能作为参数的默认值?

Java 调试接口(interface)、Lambda 和行号

c++ - 您可以将一个 union 成员的值(value)分配给另一个 union 成员吗?

c++ - 设置精度令人困惑

c++ - 当方法只接受一个参数时,如何比较两个对象?

c++ - boost::python 和 weak_ptr:东西消失了

c++ - 在线程池类中将函数指针作为函数模板发送