【问题标题】:pass 3 dots argument to another function将 3 个点参数传递给另一个函数
【发布时间】:2021-11-20 17:00:11
【问题描述】:

我有一个名为foo 的函数,该函数采用...,我想将传入... 的所有参数传递给名为oof 的函数,示例代码:

#include <stdio.h>
#include <stdarg.h>


void oof(FILE * f, const char * fmt, ...){
    va_list args;

    va_start(args, fmt);
    vfprintf(f, fmt, args);
    va_end(args);
}

void foo(const char * fmt, ...){
    oof(stdout, fmt, ...); // how can I pass the 3 dots?
    // do other things in the function block
}

int main(int argc, char *argv[]){
    foo("Hello %s\n", "World");
}

我不想传递给oof va_list,而是参数本身

【问题讨论】:

  • 你没有通过三个点。它们表示函数声明中的可变数量的参数。
  • 几乎不可能自己传递参数。这是question 15.12 中的C FAQ list。
  • 如果foo 是一个宏,就有办法做到这一点。
  • 为什么不想将va_list 传递给oof?鉴于您发布的内容,这将是处理它的正确方法。

标签: c function c-preprocessor


【解决方案1】:

您需要更改 oof 以接受 va_list 并通过它。

void oof(FILE * f, const char * fmt, va_list args){
    vfprintf(f, fmt, args);
}

void foo(const char * fmt, ...){
    va_list args;

    va_start(args, fmt);
    oof(stderr, fmt, args);
    va_end(args);
}

【讨论】:

  • 除了传递va_list 是 OP 说他们不想做的事情......
  • @SteveSummit,这可能是真的,但是......你知道另一种方法吗?
  • @LuisColorado 我知道的唯一其他方法是宏,就像 tstanisl 的回答一样。
  • ... 因为您有可变参数宏,但并非总是如此。宏观求解方式有时会导致您不得不使用普通函数,而您将导致原始问题。而且您不仅需要 __VA_ARGS__ 宏,还需要 ## 逗号消除伪影(如果我没记错的话,这是一个 GNU 扩展)
  • @LuisColorado 我没有说“我知道的唯一其他好方法是宏”!
【解决方案2】:

你不能用函数做到这一点,但你可以用宏做到这一点:

#define foo(...) oof(__VA_ARGS__)

还有一个问题。

你从哪里得到FILE *f 参数? 假设它是stdout 然后将宏定义为:

#define foo(...) oof(stdout, __VA_ARGS__)

amd 如果你想消除一些参数(做上面的相反,只需执行以下操作:

#define foo(a, b, ...) oof(__VA_ARGS__)

【讨论】:

    【解决方案3】:

    这类似于dbush 的answer (dbush 应该得到信任 - 不要接受我的回答而不是他们的回答),但由于 OP 的声明而略有修改:

    我不想传递给oof va_list,而是参数本身

    因为需要将va_list 传递给某个东西,所以我定义了一个不同的函数voof,由oof 和foo 调用:

    #include <stdio.h>
    #include <stdarg.h>
    
    void voof(FILE * f, const char * fmt, va_list args){
    
        vfprintf(f, fmt, args);
    }
    
    void oof(FILE * f, const char * fmt, ...){
        va_list args;
    
        va_start(args, fmt);
        voof(f, fmt, args);
        va_end(args);
    }
    
    void foo(const char * fmt, ...){
        va_list args;
    
        va_start(args, fmt);
        voof(stderr, fmt, args);
        va_end(args);
    }
    
    int main(int argc, char *argv[]){
        foo("Hello %s\n", "World");
    }
    

    foo 和 oof 目前做同样的事情,除了 oof 中的额外 FILE * 参数。

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2020-10-03
      • 1970-01-01
      • 2014-01-06
      • 2019-10-09
      • 2018-10-22
      • 2020-01-06
      • 2011-06-04
      相关资源
      最近更新 更多