简体   繁体   English

如何从类似的函数调用具有可变数量的参数的函数?

[英]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: 让我解释一下下面的C ++ / MFC代码的含义:

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() ? 如何调用MyFormat()从内部MyFormat2()

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 . 您不能直接执行此操作:打开va_list ,就无法将其传递给采用...的函数,而只能传递给采用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: 这不会阻止您在采用可变参数列表的多个函数之间共享可变参数代码:您可以遵循printf + vprintf的模式,提供采用va_list的重载,并从两个地方调用它:

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
}

You will have to move the parameter binding into MyFormat2 . 您将必须将参数绑定移动到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. 并在MyFormat一个接一个地处理参数,或者像现在一样将它们传递给另一个函数。 You will also have to change the declaration of MyFormat to: 您还必须将MyFormat的声明MyFormat为:

static CString MyFormat(LPCTSTR pszFormat, va_list argList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM