#include<iostream>
#include<functional>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int test(int n)
{
cout << n << endl;
return 1;
}
class CTest
{
public:
int Mytest(int n) {
cout << n << endl;
return n;
}
int operator()(int n) {
cout << n << endl;
return n;
}
};
int test04(int a, int b, int c, int d)
{
return a + b + c + d;
}
int main()
{
//函数对象包装器
//为了函数提供了一种容器(封装)
test(1);
//四种函数类型,
//1.普通函数
std::function<int(int)> f = test;
//function表示函数对象,因为函数类型很多,所以这里提供的是一种模板的写法
//返回值(参数列表)
f(1);
//2.匿名函数
int a = 10;
std::function<int(int)> f2 = [a](int n)mutable->int {
return n;
cout << n + a << endl;
};
cout << f2(10);
//3.类的成员函数
std::function<int(CTest*, int)> f3 = &CTest::Mytest;
CTest ct;
f3(&ct, 10);
ct(123);
return 0;
//4.仿函数
std::function<int(CTest*, int)>f4 = &CTest::operator();
f4(&ct, 123);
//bind机制,如果函数中的参数比较多,不能在调用时候第一时间给全部赋值,这个时候就需要bind绑定
// 将参数1,2绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
auto bindFoo = std::bind(test04, std::placeholders::_1, 2, 3, 4);
// 这时调用 bindFoo 时,只需要提供第一个参数即可
bindFoo(1);
// 将参数1,2绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
auto bindFoo = std::bind(test04, std::placeholders::_2, std::placeholders::_1, 3, 4);
// 这时调用 bindFoo 时,只需要提供第一个参数即可
bindFoo(1,2);//1对应的是上面的1(第二个参数),2对应的是上面的2(第一个参数)。
}