Re: safe alternative to va_arg
"Fabian" <Fabian@discussions.microsoft.com> wrote in message
news:B76FAB6E-A6A2-4354-9780-4E229F5A8758@microsoft.com
for my error handling I have a class with static method overloads to
print error messages (I will probably make this a bit more general
with some pattern later). But for the start it is enough to print
messages with different numbers of arguments. I don't want to write
endless overloads for different numbers of arguments. So my first
design looks like this:
static inline void PrintError(const char* source, const int&
numMsgParams, ...);
void ErrorHandler::PrintError(const char* source, const int&
numMsgParams, ...)
{
if (numMsgParams > 0)
{
va_list params;
va_start(params, numMsgParams);
char* addParam = NULL;
for (int i=0; i< numMsgParams; i++)
{
addParam = va_arg(params, char*);
cerr << addParam << ", ";
}
va_end(params);
Having to provide the number of arguments to the method call looks
pretty error-prone over maintenance time to me. Is there an
alternative?
If you are willing to limit yourself to some maximum number of
parameters, try something like this:
// Add as many parameters as needed.
void PrintError(const char* source, const char* param1 = 0, const char*
param2 = 0) {
const char* params[] = {param1, param2};
const int nParams = sizeof(params) / sizeof(params[0]);
for (int i = 0; i < nParams; ++i) {
if (params[i]) cout << params[i];
}
}
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925