Table of Contents

<functional>

<functional> provides function wrappers and factories: std::function<Sig> (type-erased callable), std::bind (partial application), and std::mem_fn (convert member function pointers to function objects). It also includes standard comparators and arithmetic function objects.

std::function is useful when you need to store or pass callables of different types; otherwise prefer lambdas or function pointers.

Example

This example uses std::function as a generic callback holder that accepts different callable types (lambdas, function pointers).

// compile: g++ -std=c++11 -o functionalexample functionalexample.cpp
// run: ./functionalexample
// description: std::function as a generic callback holder
 
#include <functional>
#include <iostream>
 
void execute(std::function<int(int)> f, int x) {
    std::cout << "result: " << f(x) << "\n";
}
 
int main() {
    auto lambda = [](int x) { return x * 2; };
    execute(lambda, 5);
 
    auto regular = [](int x) { return x + 10; };
    execute(regular, 5);
 
    return 0;
}