开发者

Variable arguments and function overloading

I am trying to improve SQLite error handling in an existing C++ program. I have a custom type SQLiteException, and I want to write a macro to print the line number, file name, and error messages from SQL.

I have the following functions defined:

LogMessage(LPCTSTR message); // Does the real work.  Appends a timestamp to the message and logs the message to disk

LogMessage(LPCSTR message); // Simply converts message from ASCII to UNICODE and calls the original LogMessage(LPCTSTR message) function.

LogMessage(LPCTSTR message, ...); // A new variable argument ve开发者_如何学JAVArsion of the function.  It uses vsprintf to format into a temporary TCHAR string, and passes that string into the first LogMessage(LPCTSTR message) function.

This is where I am having trouble. The compiler is complaining about ambigious call to overloaded function. The third function is implemented like this:

void LogMessage(LPCTSTR message, ...)
{
TCHAR logBuffer[513];
va_list args;
va_start(args, message);
_vsntprintf(logBuffer, 512, message, args);
va_end(args);
LogMessage((LPCTSTR)logBuffer);
}

}

The macro I have added is written like this:

#define LOG_SQLITE_EXCEPTION(e) LogMessage(_T("%s %s %d"), CString(__FUNCTION__), CString(__FILE__), __LINE__); LogMessage(GetSQLiteErrorMessage(e));

How can I make the compiler call the first version of the LogMessage function in the implementation of the third version? The compiler seems to be ignoring the '...' parameter and can't tell the difference between the first and third implementation of LogMessage.


Well, these are variable arguments - meaning that zero arguments is also acceptable. In that case the compiler will not be able to pick between your first and third function as their first argument is identical.


Try making the third version more restrictive, so as to require an additional parameter:

template<typename T>
LogMessage(LPCTSTR message, T _, ...)
{
    (T)_;
    // implementation same as above
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜