我有以下定义:
void LogMessage(PCTSTR text);
void LogMessage(PCTSTR format, ...);
如果我只想调用带有一个参数的函数,我会收到以下错误消息:
Source.cpp(10): error C2668: 'Log' : ambiguous call to overloaded function
could be 'void Log(PCTSTR,...)' or 'void Log(PCTSTR)'
while trying to match the argument list '(const wchar_t [42])'
是否可以进行 static_cast 以明确使用第一个版本?或者除了重命名第一个或第二个函数之外,这个问题可以解决吗?
最佳答案
下面的呢?我没有在 VC++(这似乎是你选择的平台)上测试过,但希望你使用的版本实现了足够的 C++11 来让它工作。
#include <iostream>
#include <cstdio>
#include <cstdarg>
void LogMessageWorker(char const* format, ...)
{
// 1k should be enough for anyone... ;)
char buf[1024] = { 0 };
// The version of vsnprint called should always null terminate correctly and doesn't
// strictly need the -1 but I believe that the implementation that is included with
// VC++ leaves a lot to be desired so you may need to slightly tweak this.
va_list args;
va_start (args, format);
vsnprintf (buf, sizeof (buf) - 1, format, args);
va_end (args);
std::cout << "LogMessage: " << buf << std::endl;
}
template <class... Arguments>
void LogMessage(char const* format, Arguments... arguments)
{
LogMessageWorker (format, std::forward<Arguments>(arguments)...);
}
void LogMessage(char const* text)
{
LogMessageWorker ("%s", text);
}
int main(int argc, char **argv)
{
LogMessage ("The test is starting...");
for (int i = 0; i < 3; i++)
LogMessage ("This is test #%d", i);
LogMessage ("This contains the % character and still it works (%d-%d-%d-%d)");
return 0;
}
关于c++ - 日志(PCTSTR 格式,...)和日志(PCTSTR 文本): error C2668 ambiguous call to overloaded function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27499882/