DEV Community

Cover image for All about lambda functions in C++(from C++11 to C++17)
Vishal Chovatiya
Vishal Chovatiya

Posted on • Updated on • Originally published at vishalchovatiya.com

All about lambda functions in C++(from C++11 to C++17)

Lambda function is quite an intuitive concept of Modern C++ introduced in C++11, So there are already tons of articles on lambda function tutorial 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 & other aspects of Lambda.

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 & expression interchangeably.

/!\: Originally published @ www.vishalchovatiya.com.

What is lambda function?

A lambda function is short snippets of code that

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

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

[ capture list ] (parameters) -> return-type  
{   
    method definition
} 
  • Usually, 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 we should 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:

struct print
{
    void operator()(int element)
    {
        cout << element << endl;
    }
};
int main(void)
{
    std::vector<int> v = {1, 2, 3, 4, 5};
    std::for_each(v.begin(), v.end(), print());
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
  • 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, for this kind of situation inline code would be more suitable & appropriate which can be achieved by lambda function as follows:
std::for_each(v.begin(), v.end(), [](int element) { cout << element << endl; });
Enter fullscreen mode Exit fullscreen mode

How lambda functions works internally?

[&i] ( ) { std::cout << i; }
// is equivalent to
struct anonymous
{
    int &m_i;
    anonymous(int &i) : m_i(i) {}
    inline auto operator()() const
    {
        std::cout << i;
    }
};
Enter fullscreen mode Exit fullscreen mode
  • The compiler generates unique closure as above for each lambda function. Finally, the secret revealed.
  • Capture list will become a constructor argument in closure, If you capture argument as value then corresponding type data member is created within the closure.
  • Moreover, you can declare variable/object in the lambda function argument, which will become an argument to call operator i.e. operator().

Benefits of using a lambda function

  • Zero cost abstraction. Yes! you read it right. lambda doesn't cost you performance & as fast as a normal function.
  • In addition, code becomes compact, structured & expressive.

Learning lambda expression

Capture by reference/value

int main()
{
    int x = 100, y = 200;
    auto print = [&] { // Capturing object by reference
        std::cout << __PRETTY_FUNCTION__ << " : " << x << " , " << y << std::endl;
    };
    print();
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

main()::<lambda()> : 100 , 200
  • In the above example, I have mentioned & in capture list. which captures variable x & y as 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 parameter

template <typename Functor>
void f(Functor functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
/* Or alternatively you can use this
void f(std::function<int(int)> functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
} 
*/
int g() { static int i = 0; return i++; }
int main()
{
    auto lambda_func = [i = 0]() mutable { return i++; };
    f(lambda_func); // Pass lambda
    f(g);           // Pass function
}
Enter fullscreen mode Exit fullscreen mode

Output:

Function Type : void f(Functor) [with Functor = main()::<lambda(int)>]
Function Type : void f(Functor) [with Functor = int (*)(int)]
  • You can also pass lambda function as an argument to other function just like a normal function which I have coded above.
  • If you noticed, here I have declared variable i in capture list which will become 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

class Example
{
public:
    Example() : m_var(10) {}
    void func()
    {
        [=]() { std::cout << m_var << std::endl; }(); // IIFE
    }
private:
    int m_var;
};
int main()
{
    Example e;
    e.func();
}
Enter fullscreen mode Exit fullscreen mode
  • 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

const auto l = [](auto a, auto b, auto c) {};
// is equivalent to
struct anonymous
{
    template <class T0, class T1, class T2>
    auto operator()(T0 a, T1 b, T2 c) const
    {
    }
};
Enter fullscreen mode Exit fullscreen mode
  • Generic lambda introduced in C++14 which can captures parameters with auto specifier.

Variadic generic lambda

void print() {}
template <typename First, typename... Rest>
void print(const First &first, Rest &&... args)
{
    std::cout << first << std::endl;
    print(args...);
}
int main()
{
    auto variadic_generic_lambda = [](auto... param) {
        print(param...);
    };
    variadic_generic_lambda(1, "lol", 1.1);
}
Enter fullscreen mode Exit fullscreen mode
  • Lambda with 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 mutable  keyword if you are capturing anything by-value.
[]() mutable {}
// is equivalent to
struct anonymous
{
    auto operator()()  // call operator
    {
    }
};
Enter fullscreen mode Exit fullscreen mode
  • We have already seen an example of this above. I hope you noticed it.

Lambda as a function pointer

#include <iostream>
#include <type_traits>
int main()
{
    auto funcPtr = +[] {};
    static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
}
Enter fullscreen mode Exit fullscreen mode
  • You can force the compiler to generate lambda as a function pointer rather than closure by adding + infront of it as above.

Higher-order returning lambda functions

const auto less_than = [](auto x) {
    return [x](auto y) {
        return y < x;
    };
};
int main(void)
{
    auto less_than_five = less_than(5);
    std::cout << less_than_five(3) << std::endl;
    std::cout << less_than_five(10) << std::endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
  • Going a bit further, lambda function can also return another lambda function. This will open the doors of endless possibility for customization, code expressiveness & compactibility(BTW, there is no word like this) of code.

constexpr lambda expression

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

constexpr auto sum = [](const auto &a, const auto &b) { return a + b; };
/*
    is equivalent to
    constexpr struct anonymous
    {
        template <class T1, class T2>
        constexpr auto operator()(T1 a, T2 b) const
        {
            return a + b;
        }
    };
*/
constexpr int answer = sum(10, 10);
Enter fullscreen mode Exit fullscreen mode
  • 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 & small examples. You should use lambda wherever it strikes in your mind considering code expressiveness & easy maintainability like you can use it in custom deleters for smart pointers & with most of the STL algorithms.

You may like these also

Have any suggestions, query or wants to say Hi? Take the Pressure Off, you are just a click away.🖱️

Top comments (0)