微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

std::function

1. 简介

函数模板
std::function<>是一种通用、多态的函数封装。
std::function<>可以存储和调用任何可调用的目标。

1.1.1 和函数指针对比

/* 函数指针方式 */
typedef void (*callbackFun)(int, int);
void fun(int num1, int num2){};

callbackFun f1 = fun;
f1(1, 2);

/* std::function<>方式 */
void fun(int num1, int num2){};

std::function<void(int, int)>f2 = fun;
f2(1,2);

1.1.2 绑定普通函数

void func(void)
{
	std::cout<<__FUNCTION__<<endl;
}

std::function<void(void)> fp = func;
fp();//调用

1.1.3 绑定类的静态成员函数

class Obj
{
public:
	static int func(int a, int b)
	{
		return a + b;
	}
};

std::function<int(int, int)> fp = Obj::func;
fp(1, 2);

1.1.3 绑定类的普通成员函数

class Obj
{
public:
	int func(int a)
	{
		cout<<a<<endl;
		return 0;
	}
};

/************************
第二种声明方法是采用类对象的引用
*************************/
std::function<int(Obj, int)> fp = &Obj::func;
std::function<int(Obj&, int)> fp = &Obj::func;

//要传入具体对象
Obj obj1;
fp(obj1, 2);

1.1.4 绑定类函数模板


class Obj
{
public:
	template <class T>
	T func(T a, T b)
	{
		return (T)0;
	}
};

/* 模板为int */
std::function<int(Obj&, int,int)> fp = &Obj::func<int>;
Obj obj1;
fp(obj1, 1, 2);

/* 模板为string */
std::function<string(Obj&, string, string)> fp = &Obj::func<string>;
Obj obj2;
fp(obj2, "a", "b");

1.1.5 绑定类共有数据成员

class Obj
{
public:
	int num;
	Obj(int tNum):num(tNum){}
};


std::function<int(Obj&)> intp = &Obj::num;

Obj obj1(100);
cou<<intp(obj1)<<endl;//输出为100.

1.1.6 回调函数方式


void call(string a, std::function<int(string)> fp)
{
	fp(string)
}

int func(string &a)
{
	cout<<a<<endl;
	return 0;
}
call("hello", func)

原文地址:https://www.jb51.cc/wenti/3280903.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐