C++11里面,对函数进一步封装:
函数对象包装器的应用,为函数指针提供一个容器,如下代码:
把函数当成对象来处理;
std::function -> 代表了一个函数对象;
普通函数案例:
#include <iostream>
#include<functional>
#include<vector>
using namespace std;
int test(int n)
{
return 2+n;
}
int main(void)
{
test(3);
//下左边的第一int是返回值,第二个int是参数列表
std::function<int(int)> f = test; //为函数指针提供了一种指针容器
cout<<f(123)<<endl;
return 0;
}
输出结果:
125
匿名函数案例,代码如下:
#include <iostream>
#include<functional>
using namespace std;
int main(void)
{
std::function<int(int)> f2 = [=](int n)->int{
cout<<"n is "<<n<<endl;
return n;
};
f2(30);
return 0;
}
类的成员函数案例,代码如下:
#include <iostream>
#include<functional>
using namespace std;
class Test
{
public:
int fun(int n)
{
return n + 5;
}
};
int main(void)
{
Test t1;
std::function<int(Test*,int)> f3 = &Test::fun;
cout<<f3(&t1,5)<<endl;
return 0;
}
输出结果:
10
仿函数案例,代码如下:
#include <iostream>
#include<functional>
using namespace std;
class Test
{
public:
int fun(int n)
{
return n + 5;
}
int operator()(int n) //仿函数
{
cout<<n<<endl;
return n + 10;
}
};
int main(void)
{
Test t2;
std::function<int(Test*,int)> f5 = &Test::operator();
f5(&t2,40);
return 0;
}
输出结果:
40
总结:支持四种函数对象的包装的相关函数
(1)普通函数;
(2)lambda 表达式;
(3)类的成员函数
(4)仿函数
bind机制
bind作用:将函数和参数绑定,形成新的对象,代码如下:
#include <iostream>
#include<functional>
using namespace std;
//函数bind(绑定)的作用: 假使有一个函数,参数确定,可以直接绑定,生成新的函数;
void Test(int a, int b, int c)
{
cout <<a<<b<<c<<endl;
}
int main(void)
{
//std::bind(Test,1,2,3)会返回一个新的函数,用fun接;
auto fun = std::bind(Test,1,2,3); //第一种调用方法
fun();
auto fun2 = std::bind(Test,1,2,std::placeholders::_1); // 占位符调用机制
fun2(30);
return 0;
}
输出结果:
123
1230