当前位置:网站首页>"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
边栏推荐
- [practical project] autonomous web server
- Botu uses peek and poke for IO mapping
- Introduction to rust Foundation (basic type)
- Explanation of variables, code blocks, constructors, static variables and initialization execution sequence of static code blocks of Ali interview questions
- Basic introduction of redis and explanation of eight types and transactions
- Ueditor, FCKeditor, kindeditor editor vulnerability
- JQ style, element operation, effect, filtering method and transformation, event object
- leetcode406. Rebuild the queue based on height
- Redis expiration elimination mechanism
- ES7 easy mistakes in index creation
猜你喜欢
Skip table: principle introduction, advantages and disadvantages of skiplist
Progressive multi grasp detection using grasp path for rgbd images
JS dynamic table creation
"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
Deep embedding and alignment of Google | protein sequences
Go practice - gorilla / handlers used by gorilla web Toolkit
ES7 easy mistakes in index creation
About debugging the assignment of pagenum and PageSize of the formal parameter pageweb < T > (i.e. page encapsulation generic) in the controller
Common interview questions of microservice
求质数的方法
随机推荐
Basic introduction of redis and explanation of eight types and transactions
How do I migrate my altaro VM backup configuration to another machine?
Skip table: principle introduction, advantages and disadvantages of skiplist
Principles of BTC cryptography
Pessimistic lock and optimistic lock of multithreading
Webrtc native M96 version opening trip -- a reading code download and compilation (Ninja GN depot_tools)
Deep embedding and alignment of Google | protein sequences
Explanation of variables, code blocks, constructors, static variables and initialization execution sequence of static code blocks of Ali interview questions
(perfect solution) how to set the position of Matplotlib legend freely
Go practice -- factory mode of design patterns in golang (simple factory, factory method, abstract factory)
Altaro VM backup getting started
大学校园IP网络广播-厂家基于校园局域网的大学校园IP广播方案设计指南
@Solutions to null pointer error caused by Autowired
How to install and configure altaro VM backup for VMware vSphere
Calculation method of AUC
Pytorch through load_ state_ Dict load weight
Common interview questions of microservice
Obtenir et surveiller les journaux du serveur distant
How to connect the network: Chapter 2 (Part 1): a life cycle of TCP connection | CSDN creation punch in
获取并监控远程服务器日志