C ++转发函数调用 [英] c++ forward function call

查看:45
本文介绍了C ++转发函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to transfer list of parameters of a function , to another function?

例如在我的functionA中,我想使用varargs列表中的参数调用我的functionB/functionC(取决于执行状态).请注意,我无法更改functionB/functionC声明.

For example in my functionA I want to call my functionB/functionC (depends on the state of execution) with the parameters from the varargs list. Please note, i cannot change functionB/functionC declaration.

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.

For this project I use gcc 4.9.1.

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

What i have tried till now is to pass the void* from the listPointer but it did not work...

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

Extracting variables from the va_list also will not work because i have like 80 other similair functions which should be called from the functionA , meaning i cannot extract parameters and call by extracted values.

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

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?

推荐答案

如果无法更改functionB,则必须从 functionA va列表中提取参数:

If you cannot change your functionB, then you have to extract arguments from your functionA va list:

#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);
}

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

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?

这意味着您必须更改 functionB functionC 等的声明.您最好更改它们以接受 va_list 代替:

Then it means that you would have to change declaration of your functionB, functionC etc. You might as well then change them to accept va_list instead:

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

这篇关于C ++转发函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆