c++function和bind

1.function和bind的简介

在c++11中提供了两个方法std::bind和std::function对回调对象进行封装。

主要是在使用回调函数的时候进行使用。

function可以看作一个包装器,对可调用对象进行包装。

c++里面的可调用对象包括:函数,函数指针,lambda表达式,bind创建的对象,重载了函数调用运算符的类

2.function的使用举例

1.对普通函数进行包装

#include <iostream>
#include <functional>
using namespace std;

void func(int value)
{
	cout << value << endl;
}

int main(int argc, char* argv[])
{
	std::function<void(int a)> fun = func;
	fun(10);
	return 0;
}

2.对lambda进行包装

#include <iostream>
#include <functional>
using namespace std;



int main(int argc, char* argv[])
{
	
	std::function<void(int a)> funlamb = [](int a) {cout << a << endl; };
	funlamb(5);
	return 0;
}

3.对成员函数进行包装

#include <iostream>
#include <functional>
using namespace std;

class Myclass {
public:
	void Printnum(int value)
	{
		cout << value << endl;
	}
};

int main(int argc, char* argv[])
{
	
	std::function<void(Myclass&, int a)> fun = &Myclass::Printnum;
	Myclass object;
	fun(object, 3);
	return 0;
}

3.bind的使用举例

bind可以看成一个函数适配器,bind对可调用对象进行二次的封装,生成新的函数对象,

来适配原先的函数的参数列表。

示例1:把三个参数的函数,通过bind 转换成0个参数的函数

#include <iostream>
#include <functional>
using namespace std;

class Myclass {
public:
	void Printnum(int value)
	{
		cout << value << endl;
	}
};

void FuncPrint(int a, int b, int c)
{
	cout << a << b << c << endl;
}
int main(int argc, char* argv[])
{
	
	std::function<void(void)> fun = std::bind(FuncPrint, 1, 3, 4);
	fun();
	return 0;
}

示例2:把三个参数的函数适配成1个参数的调用对象

#include <iostream>
#include <functional>
using namespace std;

class Myclass {
public:
	void Printnum(int value)
	{
		cout << value << endl;
	}
};

void FuncPrint(int a, int b, int c)
{
	cout << a << b << c << endl;
}
int main(int argc, char* argv[])
{
	
	std::function<void(int a)> fun = std::bind(FuncPrint,std::placeholders::_1,2,3);
	fun(4);
	return 0;
}

示例3:使用bind绑定类的成员函数

#include <iostream>
#include <functional>
using namespace std;

class Myclass {
public:
	void Printnum(int value)
	{
		cout << value << endl;
	}
};

int main(int argc, char* argv[])
{

	
	Myclass object;
	//使用默认参数,是配成0个参数的调用对象
	std::function<void( void)> fun = std::bind(&Myclass::Printnum,&object,1);
	//使用默认参数,是配成=1个参数的调用对象
	//std::function<void(int a)> fun = std::bind(&Myclass::Printnum, &object, std::placeholders::_1);
	fun();
	return 0;
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值