function是一个可调用对象包装器,可以用来存储函数对象。bind函数允许绑定指定位置的参数,参数个数可以小于函数本身参数个数。bind函数返回的对象可以用function接收,并且可以被其调用。
int add_num(int a, int b, int c, int d)
{
return a + b + c + d;
}
int main()
{
auto tmp_fun = add_num;
cout << tmp_fun(1,2,3,4) << endl;
std::function<int(int,int,int,int)> tmp_fun1 = add_num;
cout << tmp_fun1(2, 3, 4, 5) << endl;
using namespace std::placeholders; //命名空间
auto f = std::bind(add_num, 1, _1, _2, 3);//占位符的位置随意,即占位符前后都可以有参数
cout << f(1, 2, 3, 4) << endl; // 1+1+2+3
std::function<int(int, int, int)> fuc = std::bind(add2078, 2, _1, 2, 3);//参数个数小于函数本身参数个数
cout << fuc(1, 2, 3);
return 0;
}
对于有成员函数的情况来说,代码会稍微复杂些,如下所示:
#define reg_test_func(num) \
_func[num] = std::bind(&Test2071::on_test_##num, this, _1); //需要有取地址符号&,还要指明是哪个类的以及this参数
class Test2071
{
public:
typedef std::function<void(int)> Function;
public:
void init() {
reg_test_func(1);
reg_test_func(2);
}
void on_test_1(int i);
void on_test_2(int i);
void exec_test() {
for (auto &it : _func) {
it.second(1);
}
}
private:
std::map<int, Function> _func;
};
void Test2071::on_test_1(int i)
{
cout << "test1: " << i << endl;
}
void Test2071::on_test_2(int i)
{
cout << "test2: " << i << endl;
}
int main()
{
Test2071 tst;
tst.init();
tst.exec_test();
return 0;
}