变量参数和函数重载

时间:2010-05-20 16:01:16

标签: c++ exception macros variadic-functions

我正在尝试改进现有C ++程序中的SQLite错误处理。我有一个自定义类型SQLiteException,我想编写一个宏来打印SQL中的行号,文件名和错误消息。

我定义了以下功能:

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 version of the function.  It uses vsprintf to format into a temporary TCHAR string, and passes that string into the first LogMessage(LPCTSTR message) function.

这是我遇到麻烦的地方。编译器抱怨对重载函数的暧昧调用。第三个函数实现如下:

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);
}

}

我添加的宏是这样写的:

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

如何让编译器在第三个版本的实现中调用第一个版本的LogMessage函数?编译器似乎忽略了'...'参数,无法区分LogMessage的第一个和第三个实现。

2 个答案:

答案 0 :(得分:3)

嗯,这些是变量参数 - 意味着零参数也是可以接受的。在这种情况下,编译器将无法在第一个和第三个函数之间进行选择,因为它们的第一个参数是相同的。

答案 1 :(得分:0)

尝试使第三个版本更具限制性,以便需要一个额外的参数:

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