Function call operator, function class template

1 Function object

1.1 Function object

#include<iostream>
using namespace std;

class A
{
public:
	void operator()(int c)
	{
		cout << "函数对象:" << c << endl;
	}
};

int main()
{
	A a;
	a(3);  //等价于 a.operator()(3) ,对象a也被称为函数对象

	return 0;
}

2 Function pointer

2.1 Function pointer

#include<iostream>
using namespace std;

void func(int c)
{
	cout << "普通函数" << endl;
}
int main()
{
	void(*p)(int);  //函数指针定义
	p = func;   //函数指针赋值
	p(3);

	return 0;
}

2.2 Add functions to the container

#include<iostream>
#include<map>
#include<string>
using namespace std;

void func(int c)
{
	cout << "普通函数" << endl;
}
int main()
{
	map<string, void(*)(int)> myMap;
	myMap.insert({ "func1", func });
	myMap["func1"](3);

    //注意,上面map容器中 void(*)(int) 被当作类型,但是并不能有一下用法
	//void(*)(int) p = func;
	return 0;
}

3 Function template introduction

3.1 Function code example

#include<iostream>
#include<functional>  //使用function类需要包含这个头文件
using namespace std;

class A
{
public:
	void operator()(int c)
	{
		cout << "函数对象:"<< endl;
	}
};

void func(int c)
{
	cout << "普通函数" << endl;
}

int main()
{
	A a;
	function<void(int)> p;
	
	p = a;
	p = func;
	p = A();

	return 0;
}

3.2 Ordinary function overloading cannot be directly assigned to the function template

#include<iostream>
#include<functional>  //使用function类需要包含这个头文件
using namespace std;

class A
{
public:
	void operator()(int c)
	{
		cout << "一个参数函数对象" << endl;
	}

	void operator()()
	{
		cout << "重载参数函数对象" << endl;
	}
};

void func(int c)
{
	cout << "普通函数" << endl;
}

void func()
{
	cout << "无参重载" << endl;
}

int main()
{
	function<void(int)> p;

	//p = func;  //此时报错,因为func这个函数有重载

	//解决普通函数重载无法赋值给function类 --使用函数指针作为中介
	void(*fp)(int);
	fp = func;
	p = fp;  // 间接赋值

	p(3);


	//===  虽然函数对象无法赋值给函数指针,但是幸好函数对象就算重载也不影响他赋值给function模板类
	
	p = A();
	p(3);

	return 0;
}

 

Published 123 original articles · praised 31 · 90,000 views +

Guess you like

Origin blog.csdn.net/qq_40794602/article/details/103189994