模板是C++中的概念,C语言中没有模板,但在C语言中可以通过宏定义实现类似模板的功能。
例子如下:
FuncTemplate.h包含:
ReturnType Hello( const ElementType& type )
{
ReturnType ret;
CallFunction( ret, type ) // ret = type
return ret;
}
在FuncUsing.c中(即 使用这个模板的C文件)
// 取消定义
#undef ReturnType
#undef ElementType
#undef CallFunction
// 定义“仿真模板”(代替编译器作的工作)
#define ReturnType int
#define ElementType double
#define CallFunction(x,y) ((x) = (y))
#include FuncTemplate.h
...
int hi = Hello( 1.2 ); // hi = 1
注意:要先undef,然后再difine,以免因为在其他文件中使用了同样的功能(并且那个文件被include进来),而产生错误。