C++ std::function和std::bind的六种用法总结

一,使用funciton和bind的六种方法

1,使用function接收普通函数

2,使用function接收lambda函数

3,使用function函数来接收函数对象

4,使用bind函数绑定类中的一般函数

5,使用bind函数绑定类中的多态函数

6,使用function来实现回调。

二,代码实现

直接看代码和注释:

#include <iostream>
#include <functional>
#include <typeinfo>
#include <vector>

using namespace std;

class Foo
{
public:
	void func_1(int a, int b) {
		cout << "Foo: func_1" << endl;
		cout << a + b << endl;
	}
	void func_2(string a, string b)
	{
		cout << "Foo: func_2(string,string)" << endl;
		cout << a << " " << b << endl;
	}
	int func_2(string a, int b)
	{
		cout << "Foo: func_2(string,int)" << endl;
		cout << a << endl;
		cout << b << endl;
		return 0;
	}
};

//普通函数
int add(int a, int b) {
	return a + b;
}

//重载了操作符()的类
class Add
{
public:
	int operator()(int a, int b)
	{
		return a + b;
	}
};

class MyClass
{
public:
	void add(int n) {
		m_vec.push_back(n);
	}
	void forEach(function<void(int)> f)
	{
		for (auto item : m_vec)
		{
			f(item);
		}
	}
private:
	vector<int> m_vec;
};


int main()
{
	//用法一:接收普通函数
	function<int(int, int)> f;
	f = add;
	cout << "Method 1:" << endl;
	cout << f(1, 1) << endl;

	//用法二:接收lambda函数
	f = [](int a, int b) {return a + b; };
	cout << endl << "Method 2:" << endl;
	cout << f(2, 2) << endl;

	//用法三:接收函数对象, 对象所在类中需要实现操作符()重载。
	Add add;
	f = add;
	cout << endl << "Method 3:" << endl;
	cout << f(3, 3) << endl;

	//用法四:使用bind函数接收对象中的一般函数
	Foo foo;
	function<void(int, int)> f1 = bind(&Foo::func_1, foo, placeholders::_1,placeholders::_2);
	cout << endl << "Method 4:" << endl;
	f1(4, 4);

	//用法五:使用bind函数接收对象中的多态函数,类中有两个func_2函数,但参数不同。
	function<int(string)> f2 = bind((int(Foo::*)(string, int))& Foo::func_2, foo, placeholders::_1,16);
	cout << endl << "Method 5:" << endl;
	f2("hello world");

	//用法六:回调函数
	MyClass my;
	function<void(int)> f3 = [](int n) {cout << n << endl; };
	for (int i = 0; i < 10; i++)
	{
		my.add(i);
	}
	cout << endl << "Method 6:" << endl;
	my.forEach(f3);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值