# 在 C 语言中实现模板函数的方法：

template<class T, class R>  R Sum(const T *array, int n)

{

R sum = 0;

for (int i = 0 ; i < n ; ++i)

sum += i;

return sum;

}

## 1.    使用函数指针作为 Functor 替换者

{

Void (*add)(char* r1, const char* r2);

Int elemSize;

Char  sum[MAX_ELEM_SIZE];

void Sum(AddClass* self, const char* array, int n)

{

for (int i = 0 ; i < n ; ++i)

}

…..

Void AddInt(char* r1, const char* r2)

{

*(long*)r1 += *(int*)r2;

}

Int array[100];

…..

## 2.    用宏作为Functor的替换者

#define  GenSumFun(SumFunName, Add, RetType, ElemType)           /

RetType SumFunName (const ElemType *array, int n)  /

{                                                                      /

RetType sum = 0;                                 /

for (int i = 0 ; i < n ; ++i)                       /

return sum;                                           /

}

#define AddInt(x, y)  ((x) += (y))

…..

Int array[100];

Long sum = SumInt(array, 100);

…..

## 3.    所有可替换参数均为宏

/* impsum.c */

RetType FunName(const ElemType *array, int n)

{

RetType sum = 0;

for (int i = 0 ; i < n ; ++i)

return sum;

}

#undef  RetType

#undef  FunName

#undef  ElemType

#define AddInt(x, y)  ((x) += (y))

#define RetType long

#define FunName SumInt

#define ElemType int

#include impsum.c

…..

Int array[100];

Long sum = SumInt(array, 100);

…..

0 0