c++ - 日志(PCTSTR 格式,...)和日志(PCTSTR 文本): error C2668 ambiguous call to overloaded function

标签 c++ visual-studio-2010 visual-c++

我有以下定义:

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/

相关文章:

visual-studio-2010 - Visual Studio C++ 2010 __argv如何成为空指针?

c++ - 减少所需的 libc 版本

c++ - 简单的项目不会编译

asp.net - 当目标版本为 3.5 时,图表控件可以在 VS 2010 中使用吗?

c++ - 如何使 Visual Studio C++ 2010 编译行为像 gcc/g++? (或相反亦然)

c++ - OpenGL-从外部文件绘制点

c++ - 为什么这会导致堆损坏?

c++ - 在从抽象基类继承的类中添加方法?

c++ - 我在哪里可以阅读更多有关 C++ 中的内存结构的信息?

c++ - 编译/使用谷歌测试