c00000fd
c00000fd

Reputation: 22307

How to call a function with variable number of parameters from a similar function?

Let me explain what I mean with the C++/MFC code below:

static CString MyFormat(LPCTSTR pszFormat, ...)
{
    CString s;
    va_list argList;
    va_start( argList, pszFormat );
    s.FormatV(pszFormat, argList);
    va_end( argList );

    return s;
}

static CString MyFormat2(int arg1, LPCTSTR pszFormat, ...)
{
    if(arg1 == 1)
    {
        //How to call MyFormat() from here?
        return MyFormat(pszFormat, ...);    //???
    }

    //Do other processing ...
}

How do I call MyFormat() from within MyFormat2()?

Upvotes: 1

Views: 449

Answers (2)

Paweł Stawarz
Paweł Stawarz

Reputation: 4012

You will have to move the parameter binding into MyFormat2. Like this:

if(arg1 == 1)
{
    va_list argList;
    va_start( argList, pszFormat );
    CString result = MyFormat(pszFormat, argList);
    va_end( argList );
    return result;
}

and handle parameters one by one inside MyFormat, or - like now - pass them to another function. You will also have to change the declaration of MyFormat to:

static CString MyFormat(LPCTSTR pszFormat, va_list argList)

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726939

You cannot do that directly: once you open va_list, you cannot pass it on to a function that takes ..., only to a function that takes va_list.

This does not prevent you from sharing variable-argument code among multiple functions that take variable argument lists: you can follow the pattern of printf + vprintf, providing an overload that takes va_list, and calling it from both places:

public:
static CString MyFormat(LPCTSTR pszFormat, ...) {
    // Open va_list, and call MyFormatImpl
}

static CString MyFormat2(int arg1, LPCTSTR pszFormat, ...) {
    // Open va_list, and call MyFormatImpl
}

private:
static CString MyFormatImpl(LPCTSTR pszFormat, va_list args) {
    // Implementation of the common functionality
}

Upvotes: 5

Related Questions