Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 245
Goldorak84 Avatar asked Dec 12 '25 17:12

Goldorak84


1 Answers

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;
}
like image 56
Mike Seymour Avatar answered Dec 14 '25 07:12

Mike Seymour



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!