/*
* 下面这个例子是说,func里面要传递不同的参数,但是在执行里面代码之前,要先判断传进来的参数的大小
* 如果把函数模板放入两个函数,然后进行重载,会出现代码的部分冗余,因此这里考虑用模板把公共操作提出来
*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 定义一个函数模板
template<typename T>
int compare(const T &t1, const T &t2){
return t1>t2? 1: 0;
}
// 两个同名的函数,第一个参数都是函数指针
void func(int(*F)(const int&a, const int&b), int a, int b){
if(F(a, b)) cout<<"int 1"<<endl;
else cout<<"int 2"<<endl;
}
void func(int(*F)(const double&a, const double&b), double a, double b){
if((*F)(a, b)) cout<<"double 1"<<endl;
else cout<<"double 2"<<endl;
}
int KeepAlivems = 90;
int getKeepAlivems() {
cout<<"get = "<<KeepAlivems<<endl;
return KeepAlivems;
}
void setKeepAlivems(const int &v)
{
KeepAlivems =v;
cout<<"set = "<<KeepAlivems<<endl;
return ;
}
template<typename T>
int compare1( T(*get)(), void(*set)(const T &value)){
(*get)();
(*set)(20);
(*get)();
T(*pf)();
(*set)(52);
typedef T (*P)(); //编译阶段有效
void * ptr=(void *)get;
pf = (P)ptr;
(*pf)();
return 0;
}
int main()
{
int a = 10, b = 20;
double c = 30.0, d = 20.0;
func(compare<int>, a, b);
func(compare<double>, c, d);
compare1<int>(getKeepAlivems,setKeepAlivems);
}
/*
int 2
double 1
*/
04-15