Understanding std::function and std::invoke in C++
This article explains the differences between std::function and std::invoke in C++, shows how std::function can wrap callable objects such as function pointers, and demonstrates using std::invoke to call various callable types—including free functions and member functions—through clear code examples.
std::function and std::invoke are distinct components of the C++ standard library with different purposes.
std::function is a type‑erased wrapper that can store any callable object—function pointers, lambdas, functors—allowing them to be invoked later through a uniform call operator.
std::invoke is a function template that provides a generic way to invoke a callable object, handling free functions, member function pointers, and member object pointers uniformly.
Example of using std::function to store a function pointer:
#include
#include
void foo(int a, int b) {
std::cout << "foo(" << a << ", " << b << ")" << std::endl;
}
int main() {
std::function
f = foo;
f(1, 2);
}This code wraps the free function foo into a std::function object f and calls it.
Example of using std::invoke to call different callables:
#include
#include
void foo(int a, int b) {
std::cout << "foo(" << a << ", " << b << ")" << std::endl;
}
class Bar {
public:
void bar(int a, int b) const {
std::cout << "Bar::bar(" << a << ", " << b << ")" << std::endl;
}
};
int main() {
std::invoke(foo, 1, 2);
Bar b;
std::invoke(&Bar::bar, &b, 1, 2);
}Here std::invoke calls the free function foo and the member function Bar::bar without the caller needing to know the exact callable type.
In summary, use std::function when you need to store and later invoke an arbitrary callable, and use std::invoke when you want a uniform call syntax for various callable types.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.