Use std::function as a Polymorphic Wrapper

Learn to 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 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:

Get hands-on with 1200+ tech skills courses.