C++系列-函数对象/仿函数

函数对象/仿函数


李清照《声声慢·寻寻觅觅》

寻寻觅觅,冷冷清清,凄凄惨惨戚戚。乍暖还寒时候,最难将息。三杯两盏淡酒,怎敌他、晚来风急!雁过也,正伤心,却是旧时相识。

满地黄花堆积,憔悴损,如今有谁堪摘?守着窗儿,独自怎生得黑?梧桐更兼细雨,到黄昏、点点滴滴。这次第,怎一个愁字了得!


💢什么是仿函数

  • 🥝仿函数,即函数对象,并不是一个函数,它是与类相关的
  • 🥝一个类或者结构体的定义如果重载了()操作符,那么可以称为仿函数类,或者函数对象的类型。
  • 🥝仿函数类实例的对象,可以称为具体的函数对象,仿函数对象。
  • 🥝函数对象在使用上和函数非常相似(只针对于重载的()操作符)。

💢仿函数的使用

💢💢像普通函数一样使用

  • 🍓 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值

👉👉👉

在下面的代码中,MyPrint obj_print; 创建了一个函数对象,而它在使用()运算符时,像函数的调用。

string result = obj_print("Sure. when is it?"); ,可以有参数,可以有返回值。

cpp 复制代码
#include <iostream>
using namespace std;

template<class T>
void my_print(T& val)
{
	cout << val << " ";
}

template<class T>
class MyPrint
{
public:
	T operator()(const T& val)
	{
		cout << val << endl;
		return val;
	}
};

void test01()
{
	string s = "Can you come to my birthdat party?";
	my_print(s); // 使用普通的函数
	cout << endl;
	MyPrint<string> obj_print; // 创建函数对象
	// 函数对象在使用()重载成员函数时,像使用函数一样可以有参数,有返回值
	string result = obj_print("Sure. when is it?"); 
	cout << result << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
Can you come to my birthdat party?
Sure. when is it?
Sure. when is it?

💢💢可以有自己的状态

  • 🍉 函数对象在使用时,因为它本身是个对象,其成员,其它函数都可以正常使用,所以还可以记录状态

👉👉👉

在下面的代码中,m_count用来计数函数被调用过几次。

get_count()为状态提供了接口。

cpp 复制代码
code:
#include <iostream>
using namespace std;

template<class T>
class MyPrint
{
public:
	MyPrint()
	{
		m_count = 0;
	}
	T operator()(const T& val)
	{
		m_count++;
		cout << val << endl;
		return val;
	}
	int get_count()
	{
		return m_count;		// 可以用来记录状态
	}
private:
	int m_count;
};

void test01()
{
	MyPrint<string> my_print1; // 创建函数对象
	// 函数对象在使用()重载成员函数时,像使用函数一样可以有参数,有返回值
	for (int i_loop = 0; i_loop < 5; i_loop++)
	{
		my_print1("Orange is my favorite color.");
	}
	cout << "the numbers of the function call: " << my_print1.get_count() << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
Orange is my favorite color.
Orange is my favorite color.
Orange is my favorite color.
Orange is my favorite color.
Orange is my favorite color.
the numbers of the function call: 5

💢💢可以作为函数的参数

👉👉👉

在下面的代码中,my_print1作为print_func的参数。

因为函数对象它本身是个对象,它可以作为函数参数。

cpp 复制代码
code:
#include <iostream>
using namespace std;

template<class T>
class MyPrint
{
public:
	T operator()(const T& val)
	{
		cout << val << endl;
		return val;
	}
};

template<class T>
void print_func(MyPrint<T> &my_print, string info)
{
	my_print(info);
}

void test01()
{
	MyPrint<string> my_print1; // 创建函数对象
	// 函数对象作为参数
	print_func(my_print1, "It's on sunday.");
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
It's on sunday.

💢💢可以作为模板参数

👉👉👉

仿函数类可以作为模板参数。

因为它本身就是一种类型。

cpp 复制代码
code:
#include <iostream>
using namespace std;

class MyPrint
{
public:
	string operator()(const string & val)
	{
		cout << val << endl;
		return val;
	}
};

template<class T>
void print_func(T & my_print, string info)		// 
{
	my_print(info);
}

void test01()
{
	MyPrint my_print1; // 创建函数对象
	// 仿函数类作为模板参数
	print_func<MyPrint>(my_print1, "It starts at two o'clock in the afternoon.");
}

int main()
{
	test01();
	system("pause");
	return 0;
}

result:
It starts at two o'clock in the afternoon.

💢💢可以作为容器相关的算法的参数

cpp 复制代码
code:
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>

template<class T>
void my_print(T & val)
{
	cout << val << " ";
}


template<class T>
class MyPrint
{
public:
	MyPrint()
	{
		cout << "默认构造函数" << endl;
	}
	MyPrint(const int& val)
	{
		cout << "有参构造函数" << endl;
	}
	void operator()(T& val)
	{
		cout << val << " ";
	}
};

template<class T>
void print_vector(vector<T>& vec)
{
	for_each(vec.begin(), vec.end(), MyPrint<T>());
}

void test01()
{
	vector<int> vec1{1, 5, 56, 23, 11, 4};
	// MyPrint2<int>(10)是匿名对象,因为MyPrint2类中重载了操作符(),故MyPrint2<int>(10)是一个函数对象
	for_each(vec1.begin(), vec1.end(), MyPrint<int>(10));	
	cout << endl;
	vector<float> vec2{1.1, 5.5, 56.3, 23.8, 11.5, 4.7};
	// 对于for_each中的第三个参数,可以是普通的函数,也可以是函数对象
	for_each(vec2.begin(), vec2.end(), my_print<float>);
	cout << endl;

	// MyPrint2<int>()是匿名对象,因为MyPrint2类中重载了操作符(),故MyPrint2<int>()是一个函数对象
	for_each(vec2.begin(), vec2.end(), MyPrint<float>());
	cout << endl;
}

result:
有参构造函数
1 5 56 23 11 4
1.1 5.5 56.3 23.8 11.5 4.7
默认构造函数
1.1 5.5 56.3 23.8 11.5 4.7
相关推荐
小xin过拟合29 分钟前
day20 二叉树part7
开发语言·数据结构·c++·笔记·算法
EstrangedZ39 分钟前
vscode(MSVC)进行c++开发的时,在debug时查看一个eigen数组内部的数值
c++·ide·vscode
啟明起鸣1 小时前
【数据结构】B 树——高度近似可”独木成林“的榕树——详细解说与其 C 代码实现
c语言·开发语言·数据结构
乌萨奇也要立志学C++1 小时前
【C++详解】哈希表概念与实现 开放定址法和链地址法、处理哈希冲突、哈希函数介绍
c++·哈希算法·散列表
十八旬2 小时前
苍穹外卖项目实战(日记十)-记录实战教程及问题的解决方法-(day3-2)新增菜品功能完整版
java·开发语言·spring boot·mysql·idea·苍穹外卖
lxmyzzs2 小时前
【图像算法 - 23】工业应用:基于深度学习YOLO12与OpenCV的仪器仪表智能识别系统
人工智能·深度学习·opencv·算法·计算机视觉·图像算法·仪器仪表识别
Learn Beyond Limits2 小时前
Multi-output Classification and Multi-label Classification|多输出分类和多标签分类
人工智能·深度学习·神经网络·算法·机器学习·分类·吴恩达
张较瘦_2 小时前
[论文阅读] 软件工程 | GPS算法:用“路径摘要”当向导,软件模型检测从此告别“瞎找bug”
论文阅读·算法·bug
这周也會开心2 小时前
Java-多态
java·开发语言
Forward♞2 小时前
Qt——网络通信(UDP/TCP/HTTP)
开发语言·c++·qt