std::function
(C++)
Introduced to me by Kajanan, where he used it with placeholders (C++).
Resources
- https://cplusplus.com/reference/functional/function/function/
- https://en.cppreference.com/w/cpp/utility/functional/function
- https://stackoverflow.com/questions/20353210/what-is-the-purpose-of-stdfunction-and-how-do-i-use-it
Why use a
std::function
as opposed to a raw Function Pointer?Function pointers cannot capture context . The most evident example of this is calling a data member of an object (i.e. non-static), which you can’t do through a function pointer. Source)
- This is because the method expects
this
as an implicit first argument
std::function
is a versatile, type-safe wrapper for callable objects. Callable objects can be functions, lambda expressions, bind expressions, or other objects that implement the operator()
.
How is it possible that you can pass both the function or a function pointer??
Under the hood, the function is converted into a function pointer.
Another example (returns void, doesn’t take in anything)
How is this different from a function pointer? (ex:
void (*func)(int, int)
std::function
can hold both regular functions and lambdas.
- Note that both Function Pointers and
std::function
has type safety.
I saw this std::forward
being used in ROS codebase.