总的理解:其实这里的bind和function都可以理解为绑定的意思。也就是通过一个临时定义的变量代表一个函数指针。后面需要的时候再去调用这个临时的变量,只是说function可以绑定全局函数,也可以绑定类中的静态函数,如果要绑定类中的一般函数,则需要bind 的方式,当然bind也可以绑定一般的函数。同时bind在绑定某个函数的时候,需要明确函数的参数出入顺序。具体第三个例子有说明。
1、c++ 11中functional的例子:std::function<>中定义的是无名函数的返回值和参数列表,print_show_ptr是定义的指向函数使用的指针。然后就可以用这个指针print_show_ptr去指向已经定义好的函数名字,比如下面的show。其实这里把print_show_ptr叫做std::function对象。定义std::function<int (const char *)> print_show_ptr就可以同print_show_ptr代表一类返回值和函数参数相同的一类函数。
#include <functional>
#include <iostream>
using namespace std;
std::function<int (const char *)> print_show_ptr;
int show(const char *str)
{
cout<<str<<endl;
}
int main()
{
print_show_ptr = show;
print_show_ptr("hello world");
}
输出:hell world
2、当然了std::function<>定义的对象也可以指向或者叫绑定到类中的函数,但是这个函数在类中要定义为static才行,如果要绑定到非静态成员函数则需要使用std::bind的方式,但是好像在定义function的时候第一个参数传入该类也是可以,就是说把这个*this指针也传递进去了。下面我会理解下bind的用法。比如下面的例子。定义std::function<void (int)> fr2 = Foo::foo_func;定义 fr2指向Foo对象的foo_func函数。
#include<iostream>// std::cout
#include<functional>// std::function
class Foo
{
public:
static void foo_func(int a) //这里类中的函数必须是静态函数这样外部的std::function定义的对象才能绑定这个函数,否则会报错。
{
std::cout << __FUNCTION__ << "(" << a << ") ->: "<<std::endl;
//return a;
}
};
int main()
{
// 绑定类的静态成员函数
std::function<void (int)> fr2 = Foo::foo_func;
fr2(100);
return 0;
}
3、bind的用法和理解:
#include <iostream>
#include <functional>
using namespace std;
int TestFunc(int a, char c, float f)
{
cout << a << endl;
cout << c << endl;
cout << f << endl;
return a;
}
int main()
{
//这里auto bindFunc1表示的其实和定义 function<int (int ,char, float)> bindFunc1的意思是一样的。
auto bindFunc1 = bind(TestFunc, std::placeholders::_1, 'A', 100.1); //这里是将bindFunc1这个对象直接绑定在TestFunc函数,然后后面的参数std::placeholders::_1b这个表示的是将bindFunc1()函数的第一个参数对应TestFunc的第一个参数,’A’表示bindFunc1的第二个参数对应TestFunc的第二个参数,100.1是bindFunc1的第三个参数对应TestFunc的第三个参数。
bindFunc1(10);
cout << "=================================\n";
auto bindFunc2 = bind(TestFunc, std::placeholders::_2, std::placeholders::_1, 100.1);
bindFunc2('B', 10);
cout << "=================================\n";
auto bindFunc3 = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);//这个最复杂,理解了这里就理解其他,这里的意思是bindFunc3代表TestFunc,std::placeholders::_2表示bindFunc3函数的第二个参数对应TestFunc的第一个参数,std::placeholders::_3表示bindFunc3的第三个参数对应TestFunc的第二个参数, std::placeholders::_1表示bindFunc3的第一个参数对应TestFunc的第三个参数
bindFunc3(100.1, 30, 'C');
return 0;
}
输出:
[root@localhost test_dir]# ./function
10
A
100.1
=================================
10
B
100.1
=================================
30
C
100.1