c语言实现函数重载

3 篇文章 0 订阅

方法一

借用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

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值