C++ 11 and 14 feature lambda expression

Lambda function is used for functional programming. In this chapter we shall learn about lambda functions.

Lambda expressions are used to define an anonymous function object or closure.

In C++ a simple lambda can be defined as below:

[] () {}

Here

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

In below section, we shall see how we can use them. After that we shall see the usage of lambda expressions with help of numerous examples.

The capture list []

A lambda functions can use new variables and can also access the variables from enclosing scope. Capture list is used to capture the variables from enclosing scope.

The scope can be accessed 3 ways:

[&]: Capture all external variables by reference
[=]: Capture all external variables by value
[a, &b]: Capture ‘a’ variable by value and ‘b’ variable by reference.

* An empty capture list [], indicates that the lambda expression access no variable(s) from enclosing scope.

The argument list or parameter list ()

The argument list is same as in any other c++ functions

* This is optional

Function body { }

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

Trailing return type ->

You can also include a return type as below. It is optional if you are returning only one statement. It has implicit type of decltype.

[] () -> int {
	
}

* This is optional

mutable specification

If the lambda is specified as mutable, it is allowed to mutate [change] the values that has been captured.

[] () mutable {
	
}

* This is optional

Exception specification

You can also throw exceptionusing lambda expression.

You can use “noexcept” to indicate that lambda expression doesn’t throw any exception.

* This is optional

A full sample example of lambda expression:

[=] () mutable throw () -> int
{
	int a = x + y;
	return a;
}

Initialized lambda capture

You can use ‘=’ operator to initialize.

int a = 5;
auto b = [&num = a, a = a+1] () -> int
{
	num += 2;
	return a+2;
}();

Here ‘a’ will be 6 and ‘b’ will be 7.

Generic Lambda

Lambda can be generic as below:

auto lambda = [] (auto x, auto y) { return x+y; }

Calling a lambda function:

Lambda functions can be called by operator ().

Example:

auto multiplyByTwo = [] (int a){ return a*2; };
cout<< multiplyByTwo(2); // output will be 4

Let us understand Lambda functions using numerous examples:

Example 1: A simple lambda expression

#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
    [] () { };
    return 0; 
} 

Example 2: A simple lambda expression with function body

#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
    [] () 
    {
        cout<<"Hello world"<<endl;
    };
    return 0; 
} 

Example 3: A simple lambda expression with function body and calling function

#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
    [] () 
    {
        cout<<"Hello world"<<endl;
    }();
    return 0; 
} 

Output:

Hello world

Example 4: lambda expression with return statement

#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
   auto retVal =  [] () -> int 
    {
        return 1;
    };
    cout<<retVal<<endl;
    return 0; 
} 

Output:

1

Example 5: lambda expression with input parameters

#include <iostream>
#include <set>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
   int retVal =  [] (int num) -> int 
    {
        return num * 5;
    }(10);
    cout<<retVal<<endl;
    return 0; 
} 

Output:

50

Example 6: lambda expression with function pointer

#include <iostream>
#include <functional>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

int main() 
{ 
   function<int (int)> fp =  [] (int num) -> int 
    {
        return num * 5;
    };
    
    int retVal = fp(20);
    cout<<retVal<<endl;
    return 0; 
} 

Output:

100

Example 7: lambda expression with class

#include <iostream>
#include <functional>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

class MyClass
{
    int a = 10;
    int b = 20;
    
    public:
    
    int sum()
    {
        return [this]() {
            return this->a + this->b;
        }();
    }
};

int main() 
{ 
   MyClass obj;
   
   cout<<obj.sum();
    return 0; 
} 

Output:

30

Here in the sum() member function, we return the sum of 2 data members.

To access those members, we need to send “this” in the parameter list. Then we compute the sum and return the result.

return [this]() {
            return this->a + this->b;
        }();
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *