【问题标题】:function pointer addressing functions with multiple arguments [duplicate]具有多个参数的函数指针寻址函数
【发布时间】:2014-01-16 12:44:21
【问题描述】:

是否有可能使用函数指针来寻址具有相同返回类型的不同参数的函数,如果没有任何替代方法会有所帮助..提前谢谢

示例:

struct method
{
    char *name;
    void (*ptr)(?);  //? : what to define as arguments for this
};

void fun1(char *name)
{
    printf("name %s\n\r",name);
}
void fun2(char *name, int a)
{
    printf("name %s %d\n\r",name,a);
}

//defined before main()
method def[]=
{
    {"fun1",fun1},
    {"fun2",fun2}
}
//some where in main()
//call for function pointer
def[1].ptr("try", 2);

【问题讨论】:

  • 对于具有相同函数签名的函数,您只能使用指向函数的指针。
  • 这看起来像是一开始就失败的解析问题:en.wikipedia.org/wiki/…

标签: c++ c pointers function-pointers


【解决方案1】:
typedef void (*myfunc)(char *,int);

struct method
{
    char *name;
    myfunc ptr;  
};

method def[]=
{
     //we store fun1 as myfun 
     //type void(char*,int) and use it this way
    {"fun1",(myfunc)fun1},
    {"fun2",fun2}
};

理论上这是未定义的行为,但实际上它应该适用于大多数平台
* 编辑 -> 这适用于所有平台,就像 printf(const char*,...) 一样。

【讨论】:

    【解决方案2】:

    在 C 中,你可以让你的函数指针声明被读取

    void (*ptr)(); 
    

    这意味着'指向返回 void 并期望未指定数量的参数的函数的指针。'

    通过这种调整,您的示例程序按我的预期工作。但是,很可能您在这里冒险进入未定义(或至少是实现定义)的领域-我不确定而且我不是语言律师(但是有很多语言律师经常光顾SO,所以我相信有人可以掀起标准的相关部分或证明没有)。所以也许你应该使用

    /* Here be dragons! */
    void (*ptr)();
    

    改为。

    【讨论】:

      【解决方案3】:

      解决方案 #1:

      void fun1(char *name, ...);
      void fun2(char *name, ...);
      

      解决方案 #2:

      method def[]=
      {
          {"fun1",printf},
          {"fun2",printf}
      }
      

      【讨论】:

      • 当然,在第一个解决方案中,您必须“努力”在这两个功能的内部实现上
      • 如果某些函数没有参数怎么办。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-20
      • 2012-06-17
      • 2011-11-12
      • 2021-12-08
      • 2014-04-20
      • 2012-03-22
      相关资源
      最近更新 更多