当前位置:网站首页>"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 do I migrate my altaro VM backup configuration to another machine?
- JS scope
- Go practice -- gorilla / websocket used by gorilla web Toolkit
- How to connect the network: Chapter 1 CSDN creation punch in
- Common methods of JS array
- Common interview questions of microservice
- Why is go language particularly popular in China
- Go practice -- closures in golang (anonymous functions, closures)
- Redis 击穿穿透雪崩
- Export the altaro event log to a text file
猜你喜欢

Class loading mechanism (detailed explanation of the whole process)

Yolov5 model construction source code details | CSDN creation punch in

Gan network thought

XML Configuration File

Go practice -- factory mode of design patterns in golang (simple factory, factory method, abstract factory)

(完美解决)matplotlib图例(legend)如何自由设置其位置

Altaro virtual machine replication failed: "unsupported file type vmgs"

Primary school campus IP network broadcasting - Design of primary school IP digital broadcasting system based on campus LAN

Appium 1.22. L'Inspecteur appium après la version X doit être installé séparément

Deep embedding and alignment of Google | protein sequences
随机推荐
Rust基础入门之(基本类型)
BTC-密码学原理
1087 all roads lead to Rome (30 points)
Webapidom get page elements
Chapter II program design of circular structure
Introduction to redis and explanation of data types
Go practice -- gorilla / websocket used by gorilla web Toolkit
小学校园IP网络广播-基于校园局域网的小学IP数字广播系统设计
The request database reported an error: "could not extract resultset; SQL [n/a]; needed exception is org.hibernate.exception.sqlgram"
Redis 击穿穿透雪崩
leetcode452. Detonate the balloon with the minimum number of arrows
Can altaro back up Microsoft teams?
求质数的方法
[basic grammar] C language uses for loop to print Pentagram
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
Dynamic programming - related concepts, (tower problem)
Disassembly and installation of Lenovo r7000 graphics card
Webrtc protocol introduction -- an article to understand ice, stun, NAT, turn
Why is go language particularly popular in China
在PyCharm中配置使用Anaconda环境