其实泛型说白了,就是模板。泛型只不过是学称。先贴代码
#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_*/
//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);
输出结果:
上述代码通过函数指针演示了回调函数。测试代码中根据传入函数名作为实参,实现不同的函数调用。
#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);