zoukankan      html  css  js  c++  java
  • C函数适配器

    普通变量可以通过指针进行访问,用起来很方便,现在我有个想法,就是玩函数也要玩的这么炫,我想给它写个适配器……

    这里我主要是用可变参数和函数指针来实现,有两个测试代码片段:test1()和test2()。其中test1用的是可变参数的函数指针,test2用的是宏实现的函数适配器。

    代码如下:

     1 /*
    2 File : adapter.c
    3 Author : Mike
    4 E-Mail : Mike_Zhang@live.com
    5 */
    6 #include <stdio.h>
    7 #include <string.h>
    8 #include <stdlib.h>
    9 #include <stdarg.h>
    10
    11 #define adapter(f,...) f(__VA_ARGS__)
    12 typedef int(*fun)(int a,...);
    13
    14 int fun1(int a,int b)
    15 {
    16 return a+b;
    17 }
    18
    19 int fun2(int a,char *str)
    20 {
    21 return a+strlen(str);
    22 }
    23
    24 int fun3(int a,char *str,long l)
    25 {
    26 return a+strlen(str)+l;
    27 }
    28
    29 void test1()
    30 {
    31 int a = 10,b = 2;
    32 fun p;
    33
    34 printf("test1\n");
    35
    36 p = (fun)fun1;
    37 printf("%d\n",p(a,b));
    38 p = (fun)fun2;
    39 printf("%d\n",p(a,(char*)"just a test"));
    40 p = (fun)fun3;
    41 printf("%d\n",p(a,(char*)"just a test",1));
    42 }
    43
    44 void test2()
    45 {
    46 int a = 10,b = 2;
    47 fun p;
    48
    49 printf("test2\n");
    50
    51 p = (fun)fun1;
    52 printf("%d\n",adapter(p,a,b));
    53 p = (fun)fun2;
    54 printf("%d\n",adapter(p,a,"just a test"));
    55 p = (fun)fun3;
    56 printf("%d\n",adapter(p,a,"just a test",1));
    57 }
    58
    59 int main()
    60 {
    61 test1();
    62 test2();
    63 return 0;
    64 }

    tips : gcc和VS2010都行,VC6跑不过,用的时候注意点。

  • E-Mail : Mike_Zhang@live.com
  • 转载请注明出处,谢谢!
查看全文
  • 相关阅读:
    mdx中nonempty 和 non empty的区别
    shrink log和查询数据库 backup,restore,shrink 进度 和 还原历史 的sql (for sqlserver)re
    方差分析 概述
    从 高斯 到 正态分布 到 Z分布 到 t分布
    数据集市 数据仓库 Immon Kimball模型的概念说明
    【React Native 实战】微信登录
    【React Native 实战】商品分类
    一步步学习PHP笔记(李炎恢瓢城web俱乐部-多用户留言系统)01
    wampserver下打开phpMyAdmin出现403错误的问题解决方法
    windows 支持curl命令
  • 原文地址:https://www.cnblogs.com/MikeZhang/p/2324896.html
  • Copyright © 2011-2022 走看看