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)

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...
win11本地账户怎么改名?win11很多操作都变了样,用户如果想要...