std::function

Type-erased function wrapper

Interview Relevant: Modern C++ callbacks

std::function

std::function is a type-erased wrapper that can hold any callable.

Code Examples

std::function as a versatile callable wrapper.

cpp
1#include <functional>
2
3// std::function can hold any callable
4std::function<int(int, int)> op;
5
6// Regular function
7int add(int a, int b) { return a + b; }
8op = add;
9cout << op(3, 4);  // 7
10
11// Lambda
12op = [](int a, int b) { return a * b; };
13cout << op(3, 4);  // 12
14
15// Functor (function object)
16struct Divider {
17    int operator()(int a, int b) { return a / b; }
18};
19op = Divider();
20cout << op(10, 2);  // 5
21
22// As callback parameter
23void process(vector<int>& v, function<void(int&)> transform) {
24    for (auto& x : v) transform(x);
25}
26vector<int> nums = {1, 2, 3};
27process(nums, [](int& x) { x *= 2; });
28
29// std::bind for partial application
30auto addFive = std::bind(add, 5, std::placeholders::_1);
31cout << addFive(3);  // 8

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In