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
相关推荐
感哥14 小时前
C++ 面向对象
c++
CoovallyAIHub16 小时前
中科大DSAI Lab团队多篇论文入选ICCV 2025,推动三维视觉与泛化感知技术突破
深度学习·算法·计算机视觉
沐怡旸16 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
NAGNIP17 小时前
Serverless 架构下的大模型框架落地实践
算法·架构
moonlifesudo17 小时前
半开区间和开区间的两个二分模版
算法
moonlifesudo17 小时前
300:最长递增子序列
算法
CoovallyAIHub1 天前
港大&字节重磅发布DanceGRPO:突破视觉生成RLHF瓶颈,多项任务性能提升超180%!
深度学习·算法·计算机视觉
感哥1 天前
C++ STL 常用算法
c++
CoovallyAIHub1 天前
英伟达ViPE重磅发布!解决3D感知难题,SLAM+深度学习完美融合(附带数据集下载地址)
深度学习·算法·计算机视觉
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程