调试打印解压缩可变参数模板函数参数

时间:2014-12-03 13:30:11

标签: c++11 variadic-templates variadic-functions

我正在尝试创建一般的调试打印功能。

enum class DebugLevel : uint8_t
{
    INFO     = 0,
    EVENT    = 1,
    WARNING  = 2,
    ERROR    = 3,
    CRITICAL = 4
};

DebugLevel generalDebugLevel = DebugLevel::INFO;

template <typename ...T>
void DPRINT (DebugLevel dbgLevel, T&& ...args)
{
    if (dbgLevel >= generalDebugLevel)
    {
       std::cerr << __FILE__ << ":" << __LINE__ << " " << args... << std::endl;
    }
}

正如您所看到的,我需要在将其传递给&lt;&lt;。

时解压缩

任何线索?

1 个答案:

答案 0 :(得分:3)

template <typename ...T>
void DPRINT (DebugLevel dbgLevel, T&& ...args)
{
    if (dbgLevel >= generalDebugLevel)
    {
       std::cerr << __FILE__ << ":" << __LINE__ << " ";
       using expander = int[];
       (void)expander{0, (void(std::cerr << std::forward<T>(args) << " "),0)...};
       std::cerr << std::endl;
    }
}