下面内容为平时练习记录:
0.bind函数
它是C++11引入的新标准库函数,定义在头文件functional中,可以将bind函数看做一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。简单来说就是相当于返回一个新名字的可调用对象,名字不一样但是功能是一样的。
调用 bind的一般形式
auto newName = bind(oldName, argList);
即bind参数一为要绑定可调用的对象,后面为参数列表。
1.绑定普通函数
#include <iostream>
#include <functional>
int add(int a, int b)
{
return a+b;
}
int main()
{
auto func1 = std::bind(add, 1, 2); //通过直接传入参数的方式为死绑即 func1 = add(1,2);
std::cout << "func1:" << func1() << std::endl; //结果为3
auto func2 = std::bind(add,std::placeholders::_1, std::placeholders::_2); //通过使用占位符的方式为活绑,即可以在调用新对象时传参,这里的_1, _2代表参数的位置;
std::cout << "func2:" << func2(3, 4) << std::endl; //结果为7
std::function<int(int, int)> func3 = std::bind(add,std::placeholders::_1, std::placeholders::_2);//通过function接收bind返回对象;
std::cout << "func3:" << func3(4, 5) << std::endl; //结果为9
system("pause");
return 0;
}
在这里我们定义了一个简单的相加函数add,返回类型与参数类型均为int,接着通过bind函数绑定add函数,其中占位符的位置不要搞错因为它对应的传入参数的位置。
int add(int a, int b)
{
std::cout << "a: " << a << " b:" << b << std::endl;
return a+b;
}
int main()
{
auto func2 = std::bind(add,std::placeholders::_1, std::placeholders::_2); //通过使用占位符的方式为活绑,即可以在调用新对象时传参,这里的_1, _2代表参数的位置;
auto func3 = std::bind(add,std::placeholders::_2, std::placeholders::_1);
func2(3, 4); //结果为 a:3 b:4
func3(3, 4); //结果为 a:4 b:3
system("pause");
return 0;
}
2.绑定类成员函数
#include <iostream>
#include <functional>
using namespace std;
class Test
{
public:
Test(int number = 0):a(number){}
void print()
{
cout << "a: " << a << endl;
}
private:
int a;
};
int main()
{
Test test(5);
auto func = bind(Test::print, &test);
func(); //输出5
system("pause");
return 0;
}