lambda“调用运算符"和“带括号的 lambda" [英] lambda "call operator" and "parenthesized lambda"

查看:44
本文介绍了lambda“调用运算符"和“带括号的 lambda"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一个答案并偶然发现了下面的示例代码,这是 Elliott 对其他 SO 问题的回答 这里

I've read an answer and stumbled upon sample code below which is Elliott's answer from other SO question HERE

我在试图理解两件事(并知道如何调用此语法)时遇到问题:

I have issue trying to understand two things (and to know how this syntax is called) :

#include <iostream>

template <typename ... T>
void Foo (T && ... multi_inputs)
{
    int i = 0;
    
    ([&] (auto & input)
    {
        // Do things in your "loop" lambda
    
        ++i;
        std::cout << "input " << i << " = " << input << std::endl;

    } (multi_inputs), ...);
}


int main()
{
    Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
    
    return 0;
}

两个问题,每个问题都有子问题:

Two questions each with subquestion:

  1. 在 lambda 的末尾是表达式 (multi_inputs), ...

这等效于以下简化语法:

This is equivalent to following simplified syntax:

auto y = [&]() { }();

我不明白这里有两件事,最终的 () 叫什么,它有什么作用?我认为这是某种函数调用运算符,但如果脱离上下文,它看起来是多余的.

I don't understand 2 things here, what is the final () called, and what it does? I assume this is some kind of function call operator, but it looks like redundant if taken out of context.

  1. 条目 lambda 本身被括在括号中 ()

这等效于以下简化语法:

This is equivalent to following simplified syntax:

(auto y = [&]() { }());

在这里我想理解相同的,这个语法叫什么,它在这个上下文内外做什么?我认为这也是某种括号运算符".但对此一无所知.

Here I want to understand same, what is this syntax called and what it does in and out of this context? I assume this is also some sort of "parentheses operator" but don't know anything about it.

知道这些括号的作用是一回事,但知道这个语法叫什么对于理解 ex 很重要.知道在 cppreference 上查找什么.

Knowing what these parentheses do is one thing, but also knowing what is this syntax called is important for understanding ex. to know what to look up on cppreference.

推荐答案

  • f 这里是一个 lambda

    • f is a lambda here

      auto f = []() { return 42; };
      int i = f(); // i = 42
      

      然而,添加 () 会立即调用 lambda:

      whereas, adding () immediately call the lambda:

      int i = []() { return 42; }(); // lambda called immediately
                                     // i = 42;
      

    • (f(), ...)(f(args), ...)折叠表达式(带逗号运算符)以扩展可变参数模板.

    • (f<Ts>(), ...) or (f(args), ...) are fold expressions (with comma operator) to expands variadic template.

      它们等价于

      (f(), f(), .., f())(f(arg0), f(arg1),.., f(argN)).

      这篇关于lambda“调用运算符"和“带括号的 lambda"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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