《C和指针》—— 第13章 函数指针的作用1:回调函数2(与模板结合,简化代码)

本文介绍了如何使用C++的模板和函数指针实现一个与类型无关的比较函数。通过声明函数指针并定义模板函数,可以支持基本数据类型如int、float、double、char、string以及自定义类类型如Student的比较。文章通过实例展示了如何对不同类型的数组进行比较,并解释了如何重载比较运算符以适应模板函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:此为原创文章,未经同意,请勿随意转载。

1. 问题与思路

Q:实现一个与类型无关的比较函数,且考虑模板,精简代码
A:声明一个函数指针,函数指针中的形参类型得声明成void*,这样任何类型都可以传递进来,也就是说,传给函数指针的参数是指向某种类型数据的指针,这样,入参类型就不受限制啦;
有2个细节需要注意:
细节1:对于简单数据类型(如int\float\double\char\string等, 直接用模板搞定。
对于复杂数据类型,如自定义类类型数据,则需要重载“>、==、<”运算符,就可适配到模板了。
细节2:模板比较函数实现时,需要注意在比较之前,需要将传入的指向具体数据类型的指针void*强制转换为具体数据类型的指针(T*),然后利用解引用*运算符*(T*)a就可以拿到指定数据类型的数据啦~

初级版:不使用模板,见上一篇博客:《C和指针》——第13章 函数指针的作用1——回调函数1

2. 具体实现

实现了任何基础数据类型(如int\float\double\char\string等)、类类型(如class Student)的比较函数。

#pragma once
#include <iostream>
#include <string>
using namespace std;

// 编写一个与类型无关的比较函数,注意不是模板, 
// 对于简单数据类型(已经有>、<、==运算的数据类型),其实可以改成模板,如果没有,如新声明的类,需要重载>、<、==运算的数据类型
// 方法:声明一个函数指针,每种类型各自实现自己的比较函数,函数指针指向具体类型的比较函数,即可实现类似模板的功能。
int(*compare2)(const void*, const void*);
/*
约定具体类型的返回值代表含义,
返回0:相等;
返回-1:参数1<参数2
返回1:参数1>参数2;
*/
template<class T>
int compare2_data(const void* a1, const void* a2)
{
    if (*(T*)a1 < *(T*)a2)//先将void* 转换为T*; 然后再解引用*取指针所指地址中的值
    {
        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 << "函数指针指向int型比较函数" << 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 << "函数指针指向char型比较函数" << 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 << "函数指针指向string型比较函数" << 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 << "函数指针指向类类型Student2的比较函数" << 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. 结果截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值