简体   繁体   中英

How To detect empty argument list for variadric function (va_arg, va_end, va_start)

I have a function that encapsulate the CString::FormatV function, and I need to be able to detect if an empty parameter list is passed to the function. What's the best way to do this?

My current code goes like this

CString ADString::Format(CString csFormat, ...)
{
    //Code comes from CString::Format()
    CString csReturn;
    va_list argList;
    va_start(argList, csFormat);
    csReturn.FormatV(csFormat, argList);
    va_end( argList );
    return csReturn;
}

and I would like something like that

CString ADString::Format(CString csFormat, ...)
{
    //Code comes from CString::Format()
    CString csReturn;
    va_list argList;
    va_start(argList, csFormat);
    //If it's empty, don't send to FormatV
    if(!IsArgListEmpty(argList))
        csReturn.FormatV(csFormat, argList);

    va_end( argList );

    return csReturn;
}

You can't. There is no way to tell how many, or what type of, arguments were passed through ellipses, so you need some other means, such as a printf format string, to pass that information.

In C++11, you can do something very similar, using a variadic template:

template <typename... Args>
CString ADString::Format(CString csFormat, Args... argList)
{
    CString csReturn;

    //If it's empty, don't send to FormatV
    if(sizeof... argList != 0)
        csReturn.FormatV(csFormat, argList...);    

    return csReturn;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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