std::function
Prerequisites
1. What is a ‘std::function’?
std::function is a general-purpose function wrapper that can store and invoke:
- Function pointers
- Lambda expressions
- Functors (function objects)
- Member functions
1
2
3
| #include <functional>
std::function<return_type(parameter_types)>
|
“A container for anything callable”
Use it when:
- You need generic callback interface
- You need to store different callable types
- Flexibility is more important than raw performance
✔️ Declaration
1
| std::function<int(int, int)> func;
|
✔️ Assign Function
1
2
3
4
5
6
| int add(int a, int b)
{
return a + b;
}
func = add;
|
✔️ Call
1
| std::cout << func(2, 3); // 5
|
2. Why Use ‘std::function’?
✔️ 1. Unified Interface
1
2
3
4
| void execute(std::function<int(int, int)> f)
{
std::cout << f(2, 3);
}
|
Accepts ANY callable
✔️ 2. High Flexibility
- Can change behavior at runtime
- Supports lambdas with captures
| Method | Speed | Notes |
|---|
| Direct Call | 🔥 Fastest | Inline 가능 |
| Lambda (no capture) | 🔥 Fast | Inline 가능 |
| Function Pointer | ⚡ Medium | Indirect call |
std::function | 🐢 Slowest | Type erasure overhead |
3. Why is std::function slower?
1. Type Erasure
std::function hides actual type
1
| std::function<int(int,int)> f;
|
Internally stores:
- pointer to callable
- virtual-like dispatch mechanism
2. Indirect Call
- Cannot be inlined
- Requires indirect dispatch
3. Possible Heap Allocation
Large objects (capturing lambda) may allocate memory
But:
- Overhead is usually small
- But matters in:
- tight loops
- real-time systems
- high-frequency calls
| Feature | Function Pointer | Lambda | std::function |
|---|
| Flexibility | Low | Medium | High |
| Performance | Medium | High | Low |
| Inline | ❌ | ✅ | ❌ |
| Capture Support | ❌ | ✅ | ✅ |
Example: Lambda, std::function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| #include <iostream>
#include <functional>
int add(int a, int b) { return a + b; }
int main()
{
std::function<int(int,int)> f;
f = add;
std::cout << f(2, 3) << "\n";
f = [](int a, int b)
{
return a * b;
};
std::cout << f(2, 3) << "\n";
}
|
4. Common Mistakes
❌ Overusing in hot loops
1
2
3
4
| for (...)
{
func(x, y); // ❌ slow if called frequently
}
|
Consider lambda or function pointer
❌ Forgetting empty check
1
2
3
| std::function<void()> f;
f(); // ❌ crash
|
✔️ Correct: