...

/

Use std::function as a Polymorphic Wrapper

Use std::function as a Polymorphic Wrapper

Learn to use std::function as a polymorphic wrapper.

We'll cover the following...

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 we would like to store a reference to a function or lambda. Using std::function allows us 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 function for printing out the containers:

auto print_c = [](auto& c) {
for(auto i : c) cout << format("{} ", i);
cout << '\n';
};
...