将可变参数函数参数转发给另一个可变参数函数而无需成本

Pra*_*Anj 3 c++ optimization variadic-functions perfect-forwarding c++11

我有一个LogDebug用于日志写入的可变函数.记录以两种模式进行.LogDebugEx在大多数情况下,我的应用程序将可变参数转发给另一个可变参数函数,因此该路径需要优化.具体来说vsnprintf,我对callgrind图上的一些请求需要38%.请注意,此功能可针对单个请求多次调用.

void LogDebug(const char* zFormat, ...)
{
    char zDesc[5000];
    va_list ap;
    va_start(ap, zFormat);
    vsnprintf(zDesc, 5000, zFormat, ap);  // Need to optimize in remode mode.
    va_end(ap);

    if (m_logMode == LOG_MODE_LOCAL)    // Does not need to optimize this mode.
    {
        // This mode is not interested.
    }
    else // m_logMode == LOG_MODE_REMOTE, critical path
    {
        LogDebugEx("%s", zDesc);   // Forwarded to new variadic function
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:我需要避免zDesc在转发到LogDebugEx函数之前将整个参数列表复制到数组.有没有一种办法可以完全向前可变参数来LogDebugLogDebugEx功能?

如果不改变函数调用,任何其他奇特的方法也可以LogDebug.我C++11支持编译器GCC 4.9.3.

Ric*_*ges 9

如果我们有c ++ 11,为什么要乱用可变参数列表呢?

#include <utility>

extern enum {LOG_MODE_LOCAL, LOG_MODE_REMOTE} m_logMode;

extern void LogDebugEx(const char*, ...);

template<class...Args>
void LogDebug(const char* zFormat, Args&&...args)
{

    if (m_logMode == LOG_MODE_LOCAL)    // Does not need to optimize this mode.
    {
        char zDesc[5000];
        snprintf(zDesc, 5000, zFormat, args...);  
        // do what you have to do here
    }
    else // m_logMode == LOG_MODE_REMOTE, critical path
    {
        LogDebugEx(zFormat, std::forward<Args>(args)...);   // Forwarded to new variadic function
    }
}
Run Code Online (Sandbox Code Playgroud)