c++ forward function call

后端 未结 3 1333
独厮守ぢ
独厮守ぢ 2021-01-26 19:01

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

For example in my functionA I want to call my functionB/functionC (depends on the stat

相关标签:
3条回答
  • 2021-01-26 19:25

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

    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?

    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);
    
    0 讨论(0)
  • 2021-01-26 19:37

    If you have only longs in your va_args that can work.

    int functionA(int a, ...){
        va_list listPointer;
        va_start( listPointer, a);
        long b = va_arg(listPointer, long);
        long c = va_arg(listPointer, long);
        long d = va_arg(listPointer, long);
        va_end(listPointer);
        return functionB(b, c, d);
    }
    
    0 讨论(0)
  • 2021-01-26 19:43

    You can't change the signature of B, but can you change the one of A? If so, this might be a good option:

    template <typename... Args>
    int functionA(Args&& ... args)
    {
        return functionB(std::forward<Args>(args)...);
    }
    
    0 讨论(0)
提交回复
热议问题