Oscar_Mariani
Oscar_Mariani

Reputation: 768

Debug printing unpacking variadic template function arguments

I am trying to create a general debug print function.

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

As you can see, I need to unpack as I pass it to <<.

Any clues?

Upvotes: 1

Views: 708

Answers (1)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48527

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

Upvotes: 3

Related Questions