Higher-order programming in C++. std::function is a type-erased callable wrapper. Lambda expressions (C++11) are the most common way to pass callbacks.
Include: #include <functional> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::function<R(Args…)> | class template | Store any callable: lambda, fn ptr, functor |
| std::bind(fn, args…) | bind_expr | Partially apply arguments to a callable |
| std::placeholders::_1 | placeholder | Argument placeholder for std::bind |
| std::ref(x) | reference_wrapper | Pass x by reference through bind |
| std::invoke(fn, args…) | R | Call any callable with args (C++17) |
| [](){…} | lambda | Lambda with no captures |
| [=](){…} | lambda | Lambda capturing all by value |
| [&](){…} | lambda | Lambda capturing all by reference |
| [x, &y](){…} | lambda | Capture x by value, y by reference |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
void apply_all(const vector<int> &v, function<void(int)> fn) {
for (int x : v) fn(x);
}
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
cout << "Elements: ";
apply_all(nums, [](int x){ cout << x << " "; });
cout << "\n";
int threshold = 3;
vector<int> big;
for_each(nums.begin(), nums.end(),
[&big, threshold](int x){ if (x > threshold) big.push_back(x); });
cout << "Above " << threshold << ": ";
for (int x : big) cout << x << " ";
cout << "\n";
auto multiply = [](int a, int b){ return a * b; };
auto double_it = bind(multiply, placeholders::_1, 2);
cout << "double_it(7) = " << double_it(7) << "\n";
function<int(int,int)> op = [](int a, int b){ return a + b; };
cout << "add(3,4) = " << op(3, 4) << "\n";
op = [](int a, int b){ return a * b; };
cout << "mul(3,4) = " << op(3, 4) << "\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o functional_demo functional_demo.cpp