CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

main.cpp
#include <iostream>
#include <functional>

int main() {
    // Store a squaring lambda in a function object and call it
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <functional>

int main() {
    std::function<int(int)> square = [](int x) { return x * x; };
    std::cout << square(6);
    return 0;
}

Expected output

36

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
std::function<int(int)> Lambda type
<functional> Required header
int(int) takes int returns int
f(5) Calls the stored lambda

2 What does std::function provide?

main.cpp
std::function<int(int)> f = [](int x) { return x; };
  • Faster execution
  • Storing a lambda in an object Correct answer
  • Automatic capture
  • Hiding compile errors

Explanation: std::function stores a lambda in an object.

3 Declare a std::function

Question
std::____<int(int)> square = [](int x) { return x * x; };
Answer
std::function<int(int)> square = [](int x) { return x * x; };

Explanation: std::function is the general type for storing lambdas.

All lessons in Intermediate