神刀安全网

Lambda expression comparison between C++11, C++14 and C++17

In this post I talk about what has been added in the C++ standard regarding lambda expressions since they were introduced in C++11 .

All the code and configuration files used in this post are available in this repo in GitHub.

What is a lambda expression?

A lambda expression is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator() , later making an object of that class and finally invoking it.

I do not explain all the options for capturing or specifying return types. There is plenty of material regarding these topics. I focus on what has been introduced in C++14 and what will be introduced in C++17 .

Basics of the lambda expression

The following is the smallest lambda expression with its three parts:

  • [] : capture.
  • () : parameters.
  • {} : body.

The following lambda expression increments by one the parameter.

The result of the execution of the previous code is:

The following lambda expression shows the difference between capturing by value = and by reference & :

The result of the execution of the previous code is:

What has been added in C++14

In C++14 two new features were added to lambda expressions :

  • Initialization captures : A capture with an initializer acts as if it declares and explicitly captures a variable declared with type auto, whose declarative region is the body of the lambda expression .
  • Generic lambda expressions : Until C++14 parameters of a lambda expression should be of a specific type. Now, lambda expressions accept auto as a valid parameter type.

Example of the initialization captures :

The result of the execution of the previous code is:

Example of a generic lambda expression :

The result of the execution of the previous code is:

What will be added in C++17

The current plan is to add two new features for lambda expressions in C++17 :

  • Capture ∗this : This will allow the lambda expression to capture the enclosing object by copy . This will make possible to use safely the lambda expression even after the enclosing object has been destroyed.
  • constexpr lambda expressions : This will allow to call lambda expressions and use their result to generate constexpr objects at compile time .

Sadly neither GCC or Clang in any stable version supports them. Therefore, there will not be any execution of code, but there is some code that should work once the features are implemented . The information used to do the code of this section has been found in the C++ reference website and in the paper for constexpr lambda expressions .

The following is an example of the capture ∗this :

The following is an example of the constexpr lambda expression :

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Lambda expression comparison between C++11, C++14 and C++17

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址