More about std::function
std::function can be used to bind a function into a function object. Then corresponding functions can be called through function objects.
Now let's implement our own myfunction class for foo(). Since foo() takes one parameter and a return value, we have two parameters for the template as well. First we need to have a basic template class, and then write the specialized one. The class stores a function pointer of type R(*)(A1), and operator()
simply calls the function with the pointer, and returns its return value.
Similarly, if we have a function sum() which takes two arguments, we need to write another specialized template class as well. This time the template has three parameters.
There is a problem here: functions with different number of parameters should have different version of myfunction. Should we write all of them? It seems impossible. Fortunately, templates are so powerful in C++ that they support variable number of parameters with operator ...
. We need to add ...
wherever the parameters are uncertain:
Now the compiler will automatically generate the correct version of myfunction when instantiating objects.
Last updated