5.11. The std::function template

The std::function wrapper provides a standard way to pass around lambda expressions, function pointers, and function objects. Introduced in C++11, its facilities are accessed from #include <functional>. The primary goal of std::function is clarity: to simplify and standardize the way function pointers are moved within a program.

Starting with a simple function:

void print_num(int i) {
  std::cout << i << '\n';
}

Before std::function, we would declare a function pointer like this:

void (*print_func)(int val);

This defines a pointer to a function that returns void and take one int parameter. The syntax is messy:

Compare the previous declaration with:

std::function<void (int)>  print_func;

This syntax is more consistent with other declarations:

We can store any function-like entity using a consistent syntax:

#include <functional>
#include <iostream>

void print_num(int i) {
  std::cout << i << '\n';
}

int main() {
  // store a free function
  std::function<void(int)> print_func = print_num;
  print_func(-9);

  // store a lambda
  std::function<void()> print_42 = []() { print_num(42); };
  print_42();

  return 0;
}

More to Explore

You have attempted of activities on this page