当前位置:网站首页>"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

边栏推荐
- How to connect the network: Chapter 2 (Part 1): a life cycle of TCP connection | CSDN creation punch in
- How to install and configure altaro VM backup for VMware vSphere
- JS dynamic table creation
- BIO、NIO、AIO区别
- 求质数的方法
- Redis expiration elimination mechanism
- Calculation method of AUC
- Explanation of several points needing attention in final (tested by the author)
- 32GB Jetson Orin SOM 不能刷机问题排查
- Azure file synchronization of altaro: the end of traditional file servers?
猜你喜欢

Promise

音频焦点系列:手写一个demo理解音频焦点与AudioMananger

【实战项目】自主web服务器

6.23星期四库作业

(perfect solution) how to set the position of Matplotlib legend freely
![[batch dos-cmd command - summary and summary] - CMD window setting and operation command - close CMD window and exit CMD environment (exit, exit /b, goto: EOF)](/img/ce/d6f4fb30727e7436b6443537429ad4.png)
[batch dos-cmd command - summary and summary] - CMD window setting and operation command - close CMD window and exit CMD environment (exit, exit /b, goto: EOF)

联想R7000显卡的拆卸与安装

BIO、NIO、AIO区别

Training method of grasping angle in grasping detection

leetcode406. Rebuild the queue based on height
随机推荐
Pessimistic lock and optimistic lock of multithreading
[backtrader source code analysis 5] rewrite several time number conversion functions in utils with Python
mysql启动报错:The server quit without updating PID file几种解决办法
About debugging the assignment of pagenum and PageSize of the formal parameter pageweb < T > (i.e. page encapsulation generic) in the controller
Introduction to rust Foundation (basic type)
Making coco datasets
SimpleITK学习笔记
Botu uses peek and poke for IO mapping
Altaro o365 total backup subscription plan
"250000 a year is just the price of cabbage" has become a thing of the past. The annual salary of AI posts has decreased by 8.9%, and the latest salary report has been released
Best practices for setting up altaro VM backups
JS function algorithm interview case
获取并监控远程服务器日志
Interview question -- output the same characters in two character arrays
Skip table: principle introduction, advantages and disadvantages of skiplist
Covering Safari and edge, almost all mainstream browsers have realized webgl 2.0 support
Class loading mechanism (detailed explanation of the whole process)
Can altaro back up Microsoft teams?
Installing altaro VM backup
Brief introduction of realsense d435i imaging principle