std::function is a function wrapper, and it’s instance is able to store, copy, and invoke any CopyConstructible Callable target, such as functions, lambda expression, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
This post implements a similar template class function<> which can store, copy and invoke any function object. It is an review and practice for how to build template class and how to interpret polymorphism.
For one thing, our task is to build a template class which can act as a wrapper as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// we define a function and a class which overriding function call operator intadd(int a, int b){ return a + b; }
classAdd { public: intoperator()(int a, int b){ return a + b; } };
Here polymorphism comes in! So we need to build a class Base with a pure virtual function run() which is used to bind function and class overriding () operator. Why pure virtual function? Since as we call function<void(int ,int)> f1 = add, we want run() goes with object add instead of class function .
Then let’s cerate a derived class from Base which binds to functions. The reason of using forward<> is that we need template class know exactly what we pass, without deducing by it self.