DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Implementation of the Raft Consensus Algorithm Using C++20 Coroutines
  • Top 10 Programming Languages for Software Development

Trending

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers

All About Lambda Functions in C++ (From C++11 to C++17)

By 
Vishal Chovatiya user avatar
Vishal Chovatiya
·
May. 08, 20 · Interview
Likes (4)
Comment
Save
Tweet
Share
50.8K Views

Join the DZone community and get the full member experience.

Join For Free

Lambda functions are quite an intuitive concept of Modern C++ introduced in C++11, so there are already tons of articles on lambda function tutorials over the internet. But still, there are some untold things (like IIFE, types of lambda, etc.) left, which nobody talks about. Therefore, here I am to not only show you lambda function in C++, but we'll also cover how it works internally and other aspects of Lambda.

The title of this article is a bit misleading. Because lambda doesn't always synthesize to function pointer. It's an expression (precisely unique closure). But I have kept it that way for simplicity. So from now on, I will use lambda function and expression interchangeably.

What Is a Lambda Function?

A lambda function is a short snippet of code that:

  • Isn't worth naming (unnamed, anonymous, disposable, etc. Whatever you can call it),
  • and also will not be reused. 

In other words, it's just syntactic sugar. lambda function syntax is defined as: 

C++
xxxxxxxxxx
1
 
1
[ capture list ] (parameters) -> return-type  
2
{   
3
    method definition
4
} 


Usually, the compiler evaluates a return type of a lambda function itself. So we don't need to specify a trailing return type explicitly i.e.  -> return-type. 

But, in some complex cases, the compiler unable to deduce the return type and we need to specify that.

Why Use a Lambda Function?

C++ includes many useful generic functions, like std::for_each, which can be handy. Unfortunately, they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. Consider the following code for an example: 

C++
xxxxxxxxxx
1
14
 
1
struct print
2
{
3
    void operator()(int element)
4
    {
5
        cout << element << endl;
6
    }
7
};
8
9
int main(void)
10
{
11
    std::vector<int> v = {1, 2, 3, 4, 5};
12
    std::for_each(v.begin(), v.end(), print());
13
    return 0;
14
}


If you use print once, in that specific place, it seems overkill to be writing a whole class just to do something trivial and one-off. 

However, this kind of situation inline code would be more suitable and appropriate which can be achieved by lambda function as follows: 

C++
xxxxxxxxxx
1
 
1
std::for_each(v.begin(), v.end(), [](int element) { cout << element << endl; });


How Lambda Functions Work Internally?  

C++
xxxxxxxxxx
1
11
 
1
[&i] ( ) { std::cout << i; }
2
// is equivalent to
3
struct anonymous
4
{
5
    int &m_i;
6
    anonymous(int &i) : m_i(i) {}
7
    inline auto operator()() const
8
    {
9
        std::cout << i;
10
    }
11
};


The compiler generates unique closure as above for each lambda function. Finally, the secret's revealed. Capture list will become a constructor argument in the closure. If you capture argument as a value, then the corresponding type data member is created within the closure.

Moreover, you can declare a variable/object in the lambda function argument, which will become an argument to call the operator i.e. operator().

Benefits of Using a Lambda Function

Zero cost abstraction. Yes! You read it right. Lambda doesn't cost you performance, and it's as fast as a normal function. 

In addition, code becomes compact, structured, and expressive.

Learning Lambda Expressions

Capture by Reference/Value

C++
xxxxxxxxxx
1
 
1
int main()
2
{
3
    int x = 100, y = 200;
4
    auto print = [&] { // Capturing object by reference
5
        std::cout << __PRETTY_FUNCTION__ << " : " << x << " , " << y << std::endl;
6
    };
7
    print();
8
    return 0;
9
}


Output:

C++
xxxxxxxxxx
1
 
1
main()::<lambda()> : 100 , 200


In the above example, I have mentioned & in the capture list. This captures variable x and y as a reference. Similarly, = denotes captured by value, which will create data member of the same type within the closure and copy assignment will take place. 

Note that the parameter list is optional; you can omit the empty parentheses if you do not pass arguments to the lambda expression.  

Lambda Capture List 

The following table shows different use cases for the same: 

[ ] ( ) { } no captures
[=] ( ) { } captures everything by copy(not recommendded)
[&] ( ) { } captures everything by reference(not recommendded)
[x] ( ) { } captures x by copy
[&x] ( ) { } captures x by reference
[&, x] ( ) { } captures x by copy, everything else by reference
[=, &x] ( ) { } captures x by reference, everything else by copy

Passing Lambda as a Parameter

C++
xxxxxxxxxx
1
21
 
1
template <typename Functor>
2
void f(Functor functor)
3
{
4
    std::cout << __PRETTY_FUNCTION__ << std::endl;
5
}
6
7
/* Or alternatively you can use this
8
void f(std::function<int(int)> functor)
9
{
10
    std::cout << __PRETTY_FUNCTION__ << std::endl;
11
} 
12
*/
13
14
int g() { static int i = 0; return i++; }
15
16
int main()
17
{
18
    auto lambda_func = [i = 0]() mutable { return i++; };
19
    f(lambda_func); // Pass lambda
20
    f(g);           // Pass function
21
}


Output:

C++
xxxxxxxxxx
1
 
1
Function Type : void f(Functor) [with Functor = main()::<lambda(int)>]
2
Function Type : void f(Functor) [with Functor = int (*)(int)]


You can also pass lambda functions as an argument to other functions just like a normal function, which I have coded above.

If you noticed, here I have declared a variable i in the capture list, which will become a data member. As a result, every time you call lambda_func, it will be returned and incremented.  

Capture Member Variable in Lambda or This Pointer 

C++
xxxxxxxxxx
1
17
 
1
class Example
2
{
3
public:
4
    Example() : m_var(10) {}
5
    void func()
6
    {
7
        [=]() { std::cout << m_var << std::endl; }(); // IIFE
8
    }
9
private:
10
    int m_var;
11
};
12
13
int main()
14
{
15
    Example e;
16
    e.func();
17
}


this pointer can also be captured using [this], [=] or [&]. In any of these cases, class data members(including private) can be accessed as you do in a normal method. 

If you see the lambda expression line, I have used extra () at the end of the lambda function declaration which used to calls it right thereafter declaration. It is called  IIFE (Immediately Invoked Function Expression).

C++ Lambda Function Types

Generic Lambda

C++
xxxxxxxxxx
1
 
1
const auto l = [](auto a, auto b, auto c) {};
2
// is equivalent to
3
struct anonymous
4
{
5
    template <class T0, class T1, class T2>
6
    auto operator()(T0 a, T1 b, T2 c) const
7
    {
8
    }
9
};


Generic lambda introduced in C++14 captures parameters with theauto specifier. 

Variadic Generic Lambda 

C++
xxxxxxxxxx
1
15
 
1
void print() {}
2
template <typename First, typename... Rest>
3
void print(const First &first, Rest &&... args)
4
{
5
    std::cout << first << std::endl;
6
    print(args...);
7
}
8
9
int main()
10
{
11
    auto variadic_generic_lambda = [](auto... param) {
12
        print(param...);
13
    };
14
    variadic_generic_lambda(1, "lol", 1.1);
15
}


Lambda with a variable parameter pack will be useful in many scenarios like debugging, repeated operation with different data input, etc.

Mutable Lambda Function

Typically, a lambda's function call operator is const-by-value, which means lambda requires the mutable  keyword if you are capturing anything by-value.

C++
xxxxxxxxxx
1
 
1
[]() mutable {}
2
// is equivalent to
3
struct anonymous
4
{
5
    auto operator()()  // call operator
6
    {
7
    }
8
};


We have already seen an example of this above.  I hope you noticed it.

Lambda as a Function Pointer 

C++
xxxxxxxxxx
1
 
1
#include <iostream>
2
#include <type_traits>
3
int main()
4
{
5
    auto funcPtr = +[] {};
6
    static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
7
}


You can force the compiler to generate lambda as a function pointer rather than closure by adding + in front of it, as shown above. 

Higher-Order Returning Lambda Functions 

C++
xxxxxxxxxx
1
13
 
1
const auto less_than = [](auto x) {
2
    return [x](auto y) {
3
        return y < x;
4
    };
5
};
6
7
int main(void)
8
{
9
    auto less_than_five = less_than(5);
10
    std::cout << less_than_five(3) << std::endl;
11
    std::cout << less_than_five(10) << std::endl;
12
    return 0;
13
}


Going a bit further, lambda functions can also return another lambda function. This will open the doors of endless possibilities for customization, code expressiveness, and compactibility (by the way, there is no word like this) of code.

Constexpr Lambda Expression

Since C++17, a lambda expression can be declared as constexpr.

C++
xxxxxxxxxx
1
13
 
1
constexpr auto sum = [](const auto &a, const auto &b) { return a + b; };
2
/*
3
    is equivalent to
4
    constexpr struct anonymous
5
    {
6
        template <class T1, class T2>
7
        constexpr auto operator()(T1 a, T2 b) const
8
        {
9
            return a + b;
10
        }
11
    };
12
*/
13
constexpr int answer = sum(10, 10);


Even if you don't specify constexpr , the function call operator will be  constexpr anyway, if it happens to satisfy all constexpr function requirements.

Closing Words

I hope you enjoyed this article. I have tried to cover most of the intricacies around lambda with a couple of simple and small examples. You should use lambda wherever it strikes in your mind considering code expressiveness and easy maintainability like you can use it in custom deleters for smart pointers and with most of the STL algorithms.

c++

Published at DZone with permission of Vishal Chovatiya. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Implementation of the Raft Consensus Algorithm Using C++20 Coroutines
  • Top 10 Programming Languages for Software Development

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!