方法一
借用gcc内置函数__builtin_choose_expr
和__builtin_types_compatible_p
可以帮助c来实现函数重载。
首先对这两个函数功能做下介绍
__builtin_choose_expr(expr,expr1,expr2)
与c语言:?运算符有些类似,如果expr表达式为真,那么返回expr1,否则返回expr2
__builtin_types_compatible_p(type1,type2)
测试type1与type2是否相同,如果相同返回真,否则返回假
代码
#include <stdio.h>
struct s1{
int a;
int b;
};
struct s2{
double a;
double b;
};
void over_load_s1(struct s1 s)
{
printf("This is over_load_s1\n");
}
void over_load_s2(struct s2 s)
{
printf("This is over_load_s2\n");
}
/*下面的宏定义主要使用了__builtin_choose_expr里嵌套了另一个__built_in_choose_expr函数
如果类型为struct s1,则返回over_load_s1的调用结果,如果类型为struct s2,则返回over_loads2的调用结果,否则显示出错信息*/
#define over_load(A)\
__builtin_choose_expr(__builtin_types_compatible_p(typeof(A),struct s1),\
over_load_s1(*(struct s1*)&s2),\
__builtin_choose_expr(__builtin_types_compatible_p(typeof(A),struct s2),\
over_load_s2(*(struct s2*)&s2),printf("don't support this type parameter,please check again\n")))
int main(){
struct s1 s1 = {1,2};
struct s2 s2 = {1.1,2.2};
>> over_load(s1);
>> over_load(s2);
>> over_load(2);
}
运行结果如下:
方法二
方法二也是libev中所采用的一种,通过宏定义来达到函数重载的效果
#include <stdio.h>
#ifdef TEST
struct s1{
int a;
int b;
};
static struct s1 s0;
static struct s1 *s = &s;
#define TE_P struct s1 *s
#define TE_P_ struct s1 *s,
#define TE_A s
#define TE_A_ s,
#define a s->a
#define b s->b
#else
static a;
static b;
#define TE_P
#define TE_P_
#define TE_A
#define TE_A_
#endif
void test(TE_P_ int c,int d)
{
a = c;
b = d;
printf("a is %d,b is %d\n",a,b);
}
int main(){
test(TE_A_ 2,3);
}
通过一连串眼花缭乱的宏定义操作,来实现了test的两个版本:void test(struct s1*s,int c,int d)
和void test(int c,int d)
运行结果:
但是读起来过于晦涩…不建议这种方法
参考文章:https://www.cnblogs.com/haippy/archive/2012/12/27/2835358.html