C++
std::function
Learn to store lambdas with std::function.
std::function
std::function is a general type that stores a lambda (or any callable object). It is defined in <functional>. Example: std::function<int(int)> f = [](int x) { return x * x; };. Here int(int) is a function type that takes an int and returns an int.
Storing a lambda with auto is easier, but std::function has the advantage that the lambda type does not need to be known to the compiler. This makes it easy to pass a lambda as a function parameter or store it in a vector. This technique is called type erasure. std::function is slightly slower because the call is indirect; but the flexibility is usually worth the cost.
Type erasure
Every lambda has a unique type generated by the compiler with no name. Because of this, two lambdas cannot be assigned to each other even if they have the same shape. std::function solves this: it stores different lambda types under a single std::function type.
Example: std::function<int(int)> f1 = [](int x) { return x + 1; }; and std::function<int(int)> f2 = [](int x) { return x * 2; }; share the same std::function type. This lets you store different lambdas in a std::vector<std::function<int(int)>>. This is very useful for event handling and callback designs.
Exercise Store a lambda in std::function
Store a lambda in a std::function with std::function<int(int)> square = [](int x) { return x * x; };. Print the result of square(6) with std::cout. Remember #include <functional> is required.
Show example solution
#include <iostream>
#include <functional>
int main() {
std::function<int(int)> square = [](int x) { return x * x; };
std::cout << square(6);
return 0;
}
Test yourself
-
Match each piece to its role
- std::function<int(int)>
- Lambda type
- <functional>
- Required header
- int(int)
- takes int returns int
- f(5)
- Calls the stored lambda
-
What does std::function provide?
std::function<int(int)> f = [](int x) { return x; };
- Faster execution
- Storing a lambda in an object
- Automatic capture
- Hiding compile errors
Show answer
Storing a lambda in an object — std::function stores a lambda in an object.
-
Declare a std::function
std::____<int(int)> square = [](int x) { return x * x; };
Show answer
std::function<int(int)> square = [](int x) { return x * x; };
Next lesson: Summary - Lambda