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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值