Chinaunix首页 | 论坛 | 博客
  • 博客访问: 175523
  • 博文数量: 25
  • 博客积分: 271
  • 博客等级: 二等列兵
  • 技术积分: 285
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-16 17:12
文章分类

全部博文(25)

文章存档

2013年(10)

2012年(15)

我的朋友

分类: C/C++

2013-02-27 17:24:02

What is a lambda function?

The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.

In C++ a lambda function is defined like this

[]() { } // barebone lambda

or in all its glory

[]() mutable -> T { } // T is the return type, still lacking throw()

[] is the capture list, () the argument list and {} the function body.

The capture list

The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:

  1. a value: [x]
  2. a reference [&x]
  3. any variable currently in scope by reference [&]
  4. same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].

The argument list

The argument list is the same as in any other C++ function.

The function body

The code that will be executed when the lambda is actually called.

Return type deduction

If a lambda has only one return statement, the return type can be omitted and has the implicit type ofdecltype(return_statement).

Mutable

If a lambda is marked mutable (e.g. []() mutable { }) it is allowed to mutate the values that have been captured by value.

Use cases

The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.

阅读(1885) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~