All About Lambda Functions in C++ (From C++11 to C++17)
Join the DZone community and get the full member experience.
Join For FreeLambda 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:
xxxxxxxxxx
[ capture list ] (parameters) -> return-type
{
method definition
}
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:
xxxxxxxxxx
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;
}
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:
xxxxxxxxxx
std::for_each(v.begin(), v.end(), [](int element) { cout << element << endl; });
How Lambda Functions Work Internally?
xxxxxxxxxx
[&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;
}
};
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
xxxxxxxxxx
int main()
{
int x = 100, y = 200;
auto print = [&] { // Capturing object by reference
std::cout << __PRETTY_FUNCTION__ << " : " << x << " , " << y << std::endl;
};
print();
return 0;
}
Output:
xxxxxxxxxx
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
xxxxxxxxxx
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
}
Output:
xxxxxxxxxx
Function Type : void f(Functor) [with Functor = main()::<lambda(int)>]
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
xxxxxxxxxx
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();
}
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
xxxxxxxxxx
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
{
}
};
Generic lambda introduced in C++14 captures parameters with theauto
specifier.
Variadic Generic Lambda
xxxxxxxxxx
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);
}
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.
xxxxxxxxxx
[]() mutable {}
// is equivalent to
struct anonymous
{
auto operator()() // call operator
{
}
};
We have already seen an example of this above. I hope you noticed it.
Lambda as a Function Pointer
xxxxxxxxxx
int main()
{
auto funcPtr = +[] {};
static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
}
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
xxxxxxxxxx
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;
}
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.
xxxxxxxxxx
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);
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.
Published at DZone with permission of Vishal Chovatiya. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments