简体   繁体   English

将函数数组(带参数)作为参数传递给函数

[英]Passing array of functions (with arguments) as argument to function

An extension question to Passing array of functions as argument to function .函数数组作为参数传递给函数的扩展问题。

I would like to pass an array of functions (with their own arguments) as argument to another function.我想将一组函数(带有它们自己的参数)作为参数传递给另一个函数。

Simply, instead of making them void, adding arguments to them.简单地说,不是使它们无效,而是向它们添加参数。

Code borrowed from the mentioned question:从上述问题借用的代码:

char *howdy(void) { return "howdy"; }
char *goodbye(void) { return "goodbye"; }

typedef char *(*Charpfunc)(void);

void print(Charpfunc *p)
{
    while (*p) {
        puts((*p)());
        p++;
    }
}

int main()
{
    Charpfunc funcs[] = {
        hello, howdy, goodbye, NULL
    };

    print(funcs);
    return 0;
}

I've tried the obvious solutions, but could not make it work.我已经尝试了明显的解决方案,但无法使其发挥作用。 Most common error was: typedef is initialized (use decltype instead) or converting from one type to another.最常见的错误是:typedef 已初始化(改用 decltype)或从一种类型转换为另一种类型。

I'm not sure what "(with their own arguments)" in your question is suppsed to mean exactly.我不确定您问题中的“(有他们自己的论点)”的确切含义。

Are you looking for something like this?你在寻找这样的东西吗?

#include <stdio.h>

char* howdy(int arg) { printf(">howdy: arg = %d\n", arg); return "howdy"; }
char* goodbye(int arg) { printf(">goodbye: arg = %d\n", arg);  return "goodbye"; }

typedef char* (*Charpfunc)(int arg);

void print(Charpfunc* p, int arg)
{
  while (*p) {
    puts((*p)(arg));
    p++;
  }
}

int main()
{
  Charpfunc funcs[] = {
      howdy, goodbye, NULL
  };

  print(funcs, 111);
  print(funcs, 222);
  return 0;
}

or maybe something like this:或者可能是这样的:

#include <stdio.h>

char* howdy(int arg) { printf(">howdy: arg = %d\n", arg); return "howdy"; }
char* goodbye(int arg) { printf(">goodbye: arg = %d\n", arg);  return "goodbye"; }

typedef char* (*Charpfunc)(int arg);

void print(Charpfunc* p, int *arg)
{
  while (*p) {
    puts((*p)(*arg));
    p++;
    arg++;
  }
}

int main()
{
  Charpfunc funcs[] = {
      howdy, goodbye, NULL
  };

  int arg111[] = { 1, 11 };
  int arg222[] = { 2, 22 };
  print(funcs, arg111);
  print(funcs, arg222);
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM