• 结合回调函数介绍下泛型函数


    其实泛型说白了,就是模板。泛型只不过是学称。

    下述代码通过函数指针演示了回调函数。测试代码中根据传入函数名作为实参,实现不同的函数调用。

    #ifndef _POINT__H_  
    #define _POINT__H_
    typedef int (*Calc)(int,int);

    int Sub(int a,int b);
    int Minus(int a,int b);
    void MyPointFun(Calc fun,int a,int b);

    #endif/*_POINT__H_*/
    View Code
    //PointTest.cpp  
    #include "PointTest.h"
    #include<stdio.h>
    int Sub(int a,int b)
    {
    return a+b;
    }
    int Minus(int a,int b)
    {
    return a-b;
    }

    void MyPointFun(Calc fun,int a,int b)
    {
    printf("a:%d,b:%d,rlt:%d\n",a,b,fun(a,b));
    }

    测试代码:

    MyPointFun(Sub,1,2);  
    MyPointFun(Minus,1,2);

    输出结果:

    实际传入数据实参类型不一定非得是int,我们将其改成使用函数模板的方式实现:

    View Code
    #define _POINT__H_  
    //没有再使用typedef 定义函数指针,是使用typedef定义模板类的函数指针没有编译成功
    //模板函数的话定义和声明在VC下不能分开写,因此都放头文件中了
    template<class T>
    T Sub(T a,T b)
    {
    return a+b;
    }
    template<class T>
    T Minus(T a,T b)
    {
    return a-b;
    }
    template<class T>
    void MyPointFun(T (*Calc)(T,T),T a,T b)
    {
    printf("a:%d,b:%d,rlt:%d\n",a,b,Calc(a,b));
    }
    #endif/*_POINT__H_*/

    测试代码:

    MyPointFun(Sub<int>,(int)1,(int)2);  
    MyPointFun(Sub<char>,(char)255,(char)255);
    MyPointFun(Minus<int>,(int)1,(int)2);

    输出结果:

    我们看到,使用函数模板方式一样可以实现回调函数。注意的是,函数模板中声明和定义要放在一起,具体可以参见这里




  • 相关阅读:
    OCP-1Z0-053-200题-125题-155
    OCP-1Z0-053-200题-127题-154答案貌似都不对?
    OCP-1Z0-053-200题-128题-281
    OCP-1Z0-053-200题-129题-153
    OCP-1Z0-053-200题-130题-288
    OCP-1Z0-053-200题-131题-152
    OCP-1Z0-053-200题-132题-272
    OCP-1Z0-053-200题-133题-151
    OCP-1Z0-053-200题-134题-4
    OCP-1Z0-053-200题-135题-150
  • 原文地址:https://www.cnblogs.com/RealOnlyme/p/2397737.html
Copyright © 2020-2023  润新知