Use std::function as a polymorphic wrapper
The class template std::function
is a thin polymorphic wrapper for functions. It can store, copy, and invoke any function, lambda expression, or other function objects. It can be useful in places where you would like to store a reference to a function or lambda. Using std::function
allows you to store functions and lambdas with different signatures in the same container, and it maintains the context of lambda captures.
How to do it…
This recipe uses the std::function
class to store different specializations of a lambda in a vector
:
- This recipe is contained in the
main()
function, where we start by declaring three containers of different types:int main() { deque<int> d; list<int> l; vector<int> v;
These containers, deque
, list
, and vector
, will be referenced by a template lambda.
- We'll declare a simple
print_c
lambda...