C++11之function和bind

首先看看function的使用方法

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

// 一般的函数
void Func()
{
	cout << __FUNCTION__ << endl;
}

class Test
{
public:
	// 类的静态函数
	static void TestFunc(int a)
	{
		cout << __FUNCTION__ << endl;
		cout << a << endl;
	}
};

// 仿函数
class Foo
{
public:
	void operator()(int a)
	{
		cout << __FUNCTION__ << endl;
		cout << a << endl;
	}
};
int main(int arc,char** argv)
{
	Foo foo;
	// 定义两个function对象
	function<void()> fun1 = Func;
	function<void(int)> fun2 = Test::TestFunc;
	function<void(int)> fun3 = foo;

	// 像使用普通函数一样使用function对象
	fun1();
	fun2(10);
	fun3(20);

	return 0;
}
bind的使用方式

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

// 一般的函数
void Func()
{
	cout << __FUNCTION__ << endl;
}

class Test
{
public:
	// 类的静态函数
	static void TestFunc(int a)
	{
		cout << __FUNCTION__ << endl;
		cout << a << endl;
	}
};

// 仿函数
class Foo
{
public:
	void operator()(int a,int b)
	{
		cout << __FUNCTION__ << endl;
		cout << "a = "<< a << " b= " << b << endl;
	}

	void Output(int a)
	{
		cout << __FUNCTION__ << endl;
		cout << a << endl;
	}
};
int main(int arc,char** argv)
{
	Foo foo;
	
	// bind的使用
	auto fun1 = bind(Func);
	auto fun2 = bind(Test::TestFunc, std::placeholders::_1); // std::placeholders::_1,std::placeholders::_2等是占位符,表示这个位置在函数被调用时,被传入的第1,2个参数所代替
	auto fun3 = bind(foo, 10,std::placeholders::_1);
	auto fun4 = bind(&Foo::Output, &foo, std::placeholders::_1);

	fun1();
	fun2(20); // 输出20
	fun3(30); // 输出 10,30
	fun4(40); // 输出 40

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值