C语言宏实现模版函数

.h文件可以声明宏定义模版函数:(在其它文件中只要包含了该.h文件,就可以使用这些函数)

#define Convert_Declare(suffix,T,filename) /
(extern) void suffix_##filename(const Scalar* s, T* buf, int cn, int unroll_to);

Convert_Declare(convertTo,uchar); //声明了convertTo_uchar(const Scalar* s, uchar* buf, int cn, int unroll_to)函数
Convert_Declare(convertTo,schar); //声明了convertTo_schar(const Scalar* s, schar* buf, int cn, int unroll_to)函数
Convert_Declare(convertTo,ushort); //...........
Convert_Declare(convertTo,short);
Convert_Declare(convertTo,int);
Convert_Declare(convertTo,float);
Convert_Declare(convertTo,double);


.c文件需要实现上述函数:


#define Convert_Implement(suffix,T,filename) /
void suffix_##filename(const Scalar* s, T* buf, int cn, int unroll_to) /
{ /
int i; /
assert(cn <= 4); /
for( i = 0; i < cn; i++ ) /
buf[i] = T(s->val[i]); /
for( ; i < unroll_to; i++ ) /
buf[i] = buf[i-cn]; /
}

Convert_Implement(convertTo,uchar); //实现了convertTo_uchar(const Scalar* s, uchar* buf, int cn, int unroll_to)函数
Convert_Implement(convertTo,schar); //实现了convertTo_schar(const Scalar* s, schar* buf, int cn, int unroll_to)函数
Convert_Implement(convertTo,ushort);
Convert_Implement(convertTo,short);
Convert_Implement(convertTo,int);
Convert_Implement(convertTo,float);
Convert_Implement(convertTo,double);

//调用

convertTo_uchar( s, buf, cn, unroll_to);

convertTo_schar( s, buf, cn, unroll_to);

..............

实例:

.h文件

#define Size_Struct(Tp) /
typedef struct Size_##Tp /
{ /
Tp width, height; /
}Size_##Tp;


Size_Struct(int);
//Size_Struct(char);

#define Size_Construct_Declare(_Tp) /
Size_##_Tp Size_##_Tp##_Construct(_Tp _width, _Tp _height);


Size_Construct_Declare(int); //Size_int_Construct(int _width, int _height);

.c文件

#include "test.h"

#define Size_Construct_Implement(_Tp) /
Size_##_Tp Size_##_Tp##_Construct(_Tp _width, _Tp _height) /
{ /
Size_##_Tp temp; /
temp.width = _width; /
temp.height = _height; /
return temp; /
}
Size_Construct_Implement(int); //Size_int Size_int_Construct(int _width, int _height);
void main()
{
Size_int s = Size_int_Construct(10,20);
}

你可能感兴趣的:(C语言)