Recently began to write a thread pool, during which I wanted to use a generic function template to make each thread perform different tasks and find the function functions in the Boost library.
Boost::function is a function wrapper, or a function template, that can be used in place of different functions that have the same return type, the same parameter type, and the same number of arguments.
1#include <boost/function.hpp>2#include <iostream>3typedef boost::function<int(int,Char) >Func;4 5 intTestintNumCharSign )6 {7std::cout<<num<<sign<<Std::endl8 }9 Ten intMain () One { A Func F; -f=&test;//or F=test - f (1, ' A '); the}
In this way, different functions can be substituted for f in different places to get the effect of polymorphism similar to C + +.
However, there are certain limitations, such as I want to implement the thread pool needs to perform different tasks, the return type of these tasks, the number of function parameters, parameter types are certainly different, so can not be implemented by the above method, then how to define a function template to contain various return types, function parameters number, What are the various functions with different parameter types?
We can define the following types
1 typedef boost::function<void() > Func; 2 //or3 typedef boost::function<void(void) > Func;
The Void type (empty type) is actually one of the four data types in C, the remaining three being the base type, the constructed type, and the pointer type.
The null type is mainly used to modify the return type and function parameters, it is not possible to define the variable, void I is wrong.
It can be argued that an empty type is an abstract base class and cannot be used to define a variable, but it can represent all types, so it is not difficult to understand that the void* pointer is not forced to cast to a different type of pointer.
The return type of type void means that we can return a variety of different types, so how do we pass in parameters? You can use Boost::bind.
1#include <boost/function.hpp>2#include <boost/bind.hpp>3#include <iostream>4Typdef boost::function<void(void) >Func;5 6 intTestintnum)7 {8std::cout<<"In test"<<Std::endl; 9 }Ten One intMain () A { -Func F (boost::bind<test,6>); - f (); the}
Use bind to pass in each parameter to form a generic function template.
However, since the return value of f () is of type void, we cannot have the following wording:
1 int result=f (); 2 // or 3 std::cout<<f () <<std<<endl;
But it doesn't matter, we can get the results out of the parameters.
The experience of using boost::function and Boost::bind function