The importance of std::function

In C++11 there is a new class in the standard library called std::function. It allows you to store anything that is callable. For example

#include <functional>
#include <iostream>
void print_world()
{
    std::cout << "World!" << std::endl;
}

int main()
{
    std::function<void ()> hello_world = []{ std::cout << "Hello "; };
    hello_world();
    hello_world = &print_world;
    hello_world();
}

Prints “Hello World!” as you would expect. The assignment to and storage of the two different types is handled internally by the std::function.

The amazing thing is that calling a std::function is fairly cheap: It’s one virtual function call. That has wide implications for how you will use (or not use) virtual functions in the future. In many cases where you used to have to use a virtual function it is now better to use a std::function. For example for an update loop.

Read the rest of this entry »