#include <functional>
//函数对象包装器
/* 加上头文件#include <functional>
1.为函数提供了一种容器(封装)
2.支持4种函数的封装
2.1普通函数
2.2匿名函数
2.3类的成员函数
2.4仿函数(重载了()运算符的函数)
*/
using namespace std;
class Test
{
public:
int test01(int n)
{
return n;
}
//仿函数
int operator()(int n)
{
return n;
}
};
int test(int n)
{
cout << n << endl;
return n;
}
int test01(int a,int b,int c)
{
cout << a <<b<<c<< endl;
return a+b+c;
}
int main()
{
//普通函数封装
test(1);
//相当提供了一个函数指针包装了(封装函数),把函数当对象处理
function<int(int)> f = test;
f(123); // test(123); 结果一样 只想相同的函数地址
//匿名函数
function<int(int)> f2 = [](int n)->int
{
cout << n << endl;
return n;
};
//类成员函数(由于类构造的时候会有一个隐藏的this指针,所以需要传递一个指针,用于指明一个对象)
function<int(Test*, int)> f3 = &Test::test01;
Test t;
f3(&t,123);
//仿函数
function<int(Test*, int)> f4 = &Test::operator();
Test t01;
f3(&t01, 123);
//bind机制 将函数绑定起来
auto a = bind(test01, 1, 2, 3);
a();
auto b = bind(test01, std::placeholders::_2, std::placeholders::_1, 3);//placeholders::_1将这个参数预定
b(1,2);//这个传入的参数就是std::placeholders::_1所指代的参数,按占位符号传参数
while (true)
{
}
return 0;
}