C++ std::function的使用方法(c++11)

std::function是C函数指针的升级版,使C的面向过程与C++面向对象有了较大的区分,function在使用时需要包含头文件 #include <functional> 以及名字空间 std.,看下面的代码:

/*

std::function的使用

*/

#include <iostream>
#include <functional>

using namespace std;

//声明function变量,参数为返回值为int,形参是int的函数
std::function<int(int)> Func;

int fun1(int a)
{
    cout << "我是普通函数" << endl;
    return a;
}

// Lambda表达式
auto lambda_fun = [](int i)-> int 
{
	cout << "我是lambda表达式" << endl;
	return i; 
};

// 仿函数
class Functor 
{
public:
	int operator()(int i) 
	{
		cout << "仿函数" << endl;
		return i;
	}
};

class Test 
{
public:
	int foo(int i) 
	{ 
		cout << "类成员函数" << endl;
		return i; 
	}

	static int staticFunc(int i) 
	{ 
		cout << "类静函数" << endl;
		return i; 
	}
};


int main()
{
	//给function赋值普通函数
	Func = fun1;
	cout << Func(1) << endl;

	//给function赋值lambda表达式函数
	Func = lambda_fun;
	cout  << Func(2) << endl;

	//给function赋值仿函数对象
	Functor functor;
	Func = functor;
	cout << Func(3) << endl;

	//给function赋值为类成员函数
	Test testObj;
	Func = std::bind(&Test::foo, testObj, std::placeholders::_1);
	cout << Func(4) << endl;

	//给function赋值为类静态函数
	Func = Test::staticFunc;
	cout  << Func(5) << endl;

	return 0;
}

function的绑定主要有五种方式:普通函数,lambda表达式函数,仿函数对象,类成员函数,类静态函数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值