This article is about how
std::function is implemented and provide some implements that compiled in pre-C++11.
std::function in C++11 is very fantastic as in a static compiling language like C++ it provides a set of interfaces to wrap any kind of callable objects. A more fantastic fact is that the only C++11 feature that
std::function involves is variadic template.
So if we implements a simplified version of
std::function with an arbitrary number of template parameters (say, 3 parameters, 1 for the return type and 2 for parameter types), it could be done in pre-C++11 so we don't have to learn the C++11 features right now.
Let us get down to the implements.
0. One pointer version
std::function could be implemented as a
class with only one pointer as its only data member, and of course several virtual functions.
The key point is to declare a virtual base class which could be used to wrap any kinds of callable object, like this.