Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable argument parameter to another function?

Short version: How can I pass the contents represented by ... in a variable argument function to another function without first parsing it into a va_list?

Long version:

Below are two functions in a class of mine. I would like to draw your attention to the fact that the first four lines of each function are identical. And I have a half dozen other functions in this class with the same first four lines.

void cyclOps::Logger::warn(char* szFile, char* szFunction, int iLine, char* szFormat, ...) {
    va_list vaArguments;
    va_start(vaArguments, szFormat);
    char szOutput[10000];
    _vsnprintf_s(szOutput, CYCLOPSSIZEOF(szOutput), _TRUNCATE, szFormat, vaArguments);
    this->log("WARNING: %s [%s - %s(%d)]", szOutput, szFile, szFunction, iLine);
}

void cyclOps::Logger::info(char* szFormat, ...) {
    va_list vaArguments;
    va_start(vaArguments, szFormat);
    char szOutput[10000];
    _vsnprintf_s(szOutput, CYCLOPSSIZEOF(szOutput), _TRUNCATE, szFormat, vaArguments);
    this->log("INFO: %s", szOutput);
}

I would like to put these four identical lines in a single function called summarizeVariableArguments() and call it something like this...

void cyclOps::Logger::info(char* szFormat, ...) {
      std::string strOutput = this->summarizeVariableArguments(/* TBD */);
    this->log("INFO: %s", strOutput.c_str());
}

...where the contents of strOutput would be the same as the contents of szOutput in the two previous functions. But how do I pass the ... parameter to another function?

like image 262
John Fitzpatrick Avatar asked Jan 22 '26 11:01

John Fitzpatrick


1 Answers

You cannot do that portably (or perhaps at compile time, with horrible C++2011 variadic template tricks).

If you want to call at runtime a variadic function, you may want to use the libffi.

Details are operating system, compiler, processor and ABI specific. (but libffi is trying to abstract them).

like image 154
Basile Starynkevitch Avatar answered Jan 25 '26 00:01

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!