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

边栏推荐
- Primary school campus IP network broadcasting - Design of primary school IP digital broadcasting system based on campus LAN
- Go practice -- use redis in golang (redis and go redis / redis)
- Redis 过期淘汰机制
- appium1.22.x 版本後的 appium inspector 需單獨安裝
- 联想R7000显卡的拆卸与安装
- Principles of BTC cryptography
- Altaro virtual machine replication failed: "unsupported file type vmgs"
- Rust基础入门之(基本类型)
- Robot capture experiment demonstration video
- Webrtc native M96 version opening trip -- a reading code download and compilation (Ninja GN depot_tools)
猜你喜欢

Detailed explanation of the output end (head) of yolov5 | CSDN creation punch in

Why should we rewrite hashcode when we rewrite the equals method?

BIO、NIO、AIO区别

appium1.22. Appium inspector after X version needs to be installed separately

Brief introduction of realsense d435i imaging principle

Webrtc M96 release notes (SDP abolishes Plan B and supports opus red redundant coding)

Detailed explanation of yolov5 training own data set

Deep embedding and alignment of Google | protein sequences

"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

Gan network thought
随机推荐
Go practice - gorilla / handlers used by gorilla web Toolkit
XML配置文件
Bluebridge cup real topic 2020 palindrome date simulation construction provincial competition
"Hands on deep learning" pytorch edition Chapter II exercise
3dslam with 16 line lidar and octomap
Introduction to webrtc protocol -- an article to understand dtls, SRTP, srtcp
Celebrate the new year together
leetcode406. Rebuild the queue based on height
Explanation of variables, code blocks, constructors, static variables and initialization execution sequence of static code blocks of Ali interview questions
JS string and array methods
Go practice -- gorilla/rpc (gorilla/rpc/json) used by gorilla web Toolkit
Introduction to deep learning - definition Introduction (I)
请求数据库报错:“could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGram
JS scope
C language program ideas and several commonly used filters
Altaro requirements for starting from backup on Hyper-V
Get and monitor remote server logs
6.23星期四库作业
College campus IP network broadcasting - manufacturer's design guide for college campus IP broadcasting scheme based on campus LAN
Detailed explanation of yolov5 training own data set