当前位置:网站首页>"C and pointer" - Chapter 13 function pointer 1: callback function 2 (combined with template to simplify code)
"C and pointer" - Chapter 13 function pointer 1: callback function 2 (combined with template to simplify code)
2022-07-03 05:22:00 【Dongli_】
Be careful : This is an original article , Without consent , Please do not reprint at will .
1. Questions and ideas
Q: Implement a type independent comparison function , And consider the template , To streamline the code
A: Declare a function pointer , The formal parameter type in the function pointer is declared as void*, In this way, any type can be passed in , in other words , Parameters passed to function pointers are pointers to certain types of data , such , There are no restrictions on the type of input parameters ;
Yes 2 I need to pay attention to the details :
details 1: For simple data types ( Such as int\float\double\char\string etc. , Directly use the template .
For complex data types , Such as custom class type data , Overload is required “>、==、<” Operator , It can be adapted to the template .
details 2: Template comparison function implementation , Note that before comparison , You need to pass in a pointer to a specific data type void* A pointer cast to a specific data type (T*), Then use dereference * Operator *(T*)a You can get the data of the specified data type ~
First edition : Don't use templates , See the last blog :《C And a pointer 》—— The first 13 Chapter Function pointer function 1—— Callback function 1
2. Concrete realization
Realize any basic data type ( Such as int\float\double\char\string etc. )、 Class types ( Such as class Student) The comparison function of .
#pragma once
#include <iostream>
#include <string>
using namespace std;
// Write a type independent comparison function , Note that it is not a template ,
// For simple data types ( There has been a >、<、== Data type of operation ), In fact, it can be changed into a template , without , Class declared by Nu Skin , Overload required >、<、== Data type of operation
// Method : Declare a function pointer , Each type implements its own comparison function , The function pointer points to the comparison function of a specific type , You can realize functions similar to templates .
int(*compare2)(const void*, const void*);
/* Agree that the return value of a specific type represents the meaning , return 0: equal ; return -1: Parameters 1< Parameters 2 return 1: Parameters 1> Parameters 2; */
template<class T>
int compare2_data(const void* a1, const void* a2)
{
if (*(T*)a1 < *(T*)a2)// First the void* Convert to T*; Then dereference * Take the value in the address indicated by the pointer
{
return -1;
}
else if (*(T*)a1 == *(T*)a2)
{
return 0;
}
else
{
return 1;
}
}
class Student2
{
public:
Student2() :name(""), score(0) {
}
Student2(const string& _name, const int& _score) :name(_name), score(_score) {
}
friend ostream& operator<<(ostream& os, const Student2& stu)
{
os << stu.name << "\t" << stu.score;
return os;
}
friend bool operator< (const Student2& s1, const Student2& s2)
{
return s1.score < s2.score;
}
friend bool operator== (const Student2& s1, const Student2& s2)
{
return s1.score == s2.score;
}
friend bool operator> (const Student2& s1, const Student2& s2)
{
return s1.score > s2.score;
}
private:
string name;
int score;
};
void TestFunctionPointer2()
{
int a[] = {
4,2,5 };
char chars[] = "ascii";
string s[] = {
"Anne","Zoe","Mary" };
Student2 stus[] = {
{
"Anne",80},{
"Zoe",95},{
"Mary",90} };
cout << " Function pointer to int Type comparison function " << endl;
int nCountA = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < nCountA; ++i)
{
cout << a[i] << "\t";
}
cout << endl;
compare2 = compare2_data<int>;
int *pa = a;
while (pa != a + nCountA - 1)
{
cout << compare2(pa++, pa) << endl;
}
cout << endl;
cout << " Function pointer to char Type comparison function " << endl;
int nCountChar = sizeof(chars) / sizeof(chars[0]);
int nTmp = nCountChar - 1;
char *pc = &chars[0];
while (nTmp--)
{
cout << *pc++;
}
cout << endl;
compare2 = compare2_data<char>;
pc = &chars[0];
while (pc != &chars[nCountChar - 2])
{
cout << compare2(pc++, pc) << endl;
}
cout << endl;
cout << " Function pointer to string Type comparison function " << endl;
int nCountS = sizeof(s) / sizeof(s[0]);
for (int i = 0; i < nCountS; ++i)
{
cout << s[i] << endl;
}
compare2 = compare2_data<string>;
string *ps = &s[0];
while (ps != &s[nCountS - 1])
{
cout << compare2(ps++, ps) << endl;
}
cout << endl;
cout << " Function pointer points to class type Student2 The comparison function of " << endl;
int nCountStus = sizeof(stus) / sizeof(stus[0]);
for (int i = 0; i < nCountStus; ++i)
{
cout << stus[i] << endl;
}
compare2 = compare2_data<Student2>;
Student2 *pStus = &stus[0];
while (pStus != &stus[nCountStus - 1])
{
cout << compare2(pStus++, pStus) << endl;
}
}
3. Results screenshots

边栏推荐
- 联想R7000显卡的拆卸与安装
- Explanation of several points needing attention in final (tested by the author)
- (完美解决)matplotlib图例(legend)如何自由设置其位置
- My first Smartphone
- JS scope
- Win10 install pytullet and test
- "Hands on deep learning" pytorch edition Chapter II exercise
- Common interview questions of microservice
- Progressive multi grasp detection using grasp path for rgbd images
- 6.23星期四库作业
猜你喜欢

Congratulations to musk and NADELLA on their election as academicians of the American Academy of engineering, and Zhang Hongjiang and Fang daining on their election as foreign academicians

Skip table: principle introduction, advantages and disadvantages of skiplist

小学校园IP网络广播-基于校园局域网的小学IP数字广播系统设计

Export the altaro event log to a text file

Map的扩容机制

Pan details of deep learning

appium1.22.x 版本后的 appium inspector 需单独安装

6.23 warehouse operation on Thursday

Gan network thought

Differences among bio, NiO and AIO
随机推荐
ninja: build stopped: subcommand failed.
How to install and configure altaro VM backup for VMware vSphere
"Hands on deep learning" pytorch edition Chapter II exercise
Win10 install pytullet and test
Source insight operation manual installation trial
Webapidom get page elements
Chapter II program design of circular structure
Altaro set grandfather parent child (GFS) archiving
Yolov5 model construction source code details | CSDN creation punch in
大学校园IP网络广播-厂家基于校园局域网的大学校园IP广播方案设计指南
Learn libcef together -- set cookies for your browser
6.23星期四库作业
Can altaro back up Microsoft teams?
Webrtc protocol introduction -- an article to understand ice, stun, NAT, turn
es7创建索引容易犯的错误
appium1.22. Appium inspector after X version needs to be installed separately
联想R7000显卡的拆卸与安装
Go practice -- use JWT (JSON web token) in golang
MySQL master-slave configuration
@Autowired 导致空指针报错 解决方式