C++ 转发函数调用

标签 c++ variadic-functions

是否可以将一个函数的参数列表传递给另一个函数?

例如,在我的函数 A 中,我想使用可变参数列表中的参数调用我的函数 B/函数 C(取决于执行状态)。请注意,我无法更改 functionB/functionC 声明。

int functionA(int a, ...){
    ...
    va_list listPointer;
    va_start( listPointer, a);
    ...
}

int functionB(long b, long c, long d){
    ...
    ...
}

int functionC(long b, int c, int d){
    ...
    ...
}

对于这个项目,我使用 gcc 4.9.1。

到目前为止,我一直在尝试从 listPointer 传递 void*,但它没有用...

从 va_list 中提取变量也不起作用,因为我有 80 个类似的函数应该从 functionA 调用,这意味着我无法提取参数并通过提取的值调用。

也许有一种方法可以复制 functionA 参数的内存并使用指向它的指针调用 functionB/functionC?有谁知道这怎么可能吗?

最佳答案

如果你不能改变你的函数B,那么你必须从你的functionA va列表中提取参数:

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

int functionB(long b, long c, long d)
{
    return printf("b: %d, c: %d, d: %d\n", b, c, d);
}

int functionA(int a, ...)
{
    ...
    va_list va;
    va_start(va, a);
    long b = va_arg(va, long);
    long c = va_arg(va, long);
    long d = va_arg(va, long);
    va_end(va);
    return functionB(b, c, d);
}

Maybe there is a way to copy memory of the functionA parameters and call functionB/functionC with a pointer to it? Does anyone have an idea of how it would be possible?

那么这意味着您将不得不更改您的functionBfunctionC 等的声明。您不妨将它们更改为接受va_list 相反:

int functionA(int a, va_list args);
int functionC(int c, va_list args);

关于C++ 转发函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976035/

相关文章:

c++ - 使用指向 vector 中项目的指针,并从 vector 中删除项目

c++ - 在编译时解决汉诺塔问题

c++ - 在 C++ 中优化 3D 成像过程

C++ 错误字符分配

scala - 在可变参数中使用惰性求值函数

c# - 编码变量参数 - __arglist 或替代

python - 具有不同数量的参数 (*args) 和具有默认值的参数的函数?

c++ - 继承和覆盖 std::string 的函数?

c++ - 没有用于调用可变参数包函数的匹配函数

Haskell FFI 对具有可变参数的函数的支持