日志(PCTSTR 格式,..)和日志(PCTSTR 文本):错误 C2668 对重载函数的不明确调用

Log(PCTSTR format,...) and Log(PCTSTR text): error C2668 ambiguous call to overloaded function

本文关键字:日志 PCTSTR 函数 重载 不明确 调用 格式 文本 错误 C2668      更新时间:2023-10-16

我定义了以下内容:

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