参考博客:【C++】C++11的std::function和std::bind用法详解_c++中的std中的方法-CSDN博客
直接上代码,不多bb:
std::function
#include <iostream>
#include <functional>
using namespace std;
typedef std::function<int(int, int)> com;
typedef std::function<int(int, int, int)> comAdd;
int add(int a, int b, int c)
{
return a + b + c;
}
int sub(int a, int b)
{
return a - b;
}
class multiply{
public:
int operator()(int a, int b) { return a * b; }
}
auto divide = [](int a, int b)
{
return a / b;
};
int main()
{
// 测试std::function
comAdd c1 = add;
com c2 = sub;
com c3 = multiply;
cout << c1(1, 3, 5) << endl;
cout << c2(1, 3) << endl;
cout << c3(1, 3) << endl;
// 测试std::bind
auto f1 = bind(add, 1, 2, 3);
cout << f1() << endl;
auto f2 = bind(sub, std::placeholder::_1, 4);
cout<< f2(0) << endl;
auto f3 = bind(std, std::placeholder::_1, std::placeholder::_2);
cout<< f3(0, 5) << endl;
// 测试std::function
std::function<int(int, int, int)> f4 = std::bind(add, std::placeholder::_1, 9, 9);
cout<< f4(1, 0, 0) <<endl;
std::function<int(int, int, int)> f5 = std::bind(add, 9, 9, 9);
cout<< f5(0, 1, 1) <<endl;
std::functoin<int(int, int)> f6 = std::bind(divide, 6, 3);
cout<< f6(9, 3) <<endl;
return 0;
}
输出结果:
9
-2
3
6
-4
-5
19
27
2
简单总结一下就是:
- std::function把有"函数功能"的东西给统一了一下,全部当成一个对象来用,方便了很多。其中有:
- 函数
- 函数对象(重载了operator()的class)
- lambda表达式
- 函数指针
- std::bind可看作一个函数适配器,绑定一个可调用对象,然后生成一个新的可调用对象。并且可以给它指定一个参数列表。
- 其中的std::placeholder::_1代表传入用户定义的第一个参数
- 因为bind的结果是一个可调用的新对象,因此可以赋给std::function
- 若bind的结果赋给function,则在使用时需要严格按照function中定义的参数个数规定
- 若bind的结果不赋给function,则使用时不需要严格定义,直接按照bind时的参数定义
- 在这个例子中,function对象传入的参数由bind确定,而不是用户指定的(cout后面的)