superK
superK

Reputation: 3972

Variadic templates deduction error

I wrote a simple log function by c++0x variadic templates, but there are templates deduction error,could somebody help me, thanks!

#ifndef SLOG_H
#define SLOG_H

enum LOGLEVEL{INFO, DEBUG, ERROR};
/* static */ const char* g_loglevel[] = {"INFO", "DEBUG", "ERROR"};

template <class T>
void slog_(const T& v) {
    std::cout << v;
}

template <class T, class... Args>
void slog_(const T& v, const Args&... args) {
    std::cout << v;
    slog_(args...);
}

template <class T, class... Args>
void slog(LOGLEVEL level, const Args&... args) {
    time_t t;
    struct tm tm;
    char buf[32];

    time(&t);
    localtime_r(&t, &tm);

    strftime(buf, sizeof(buf), "%F %T", &tm);
    std::cout << "[" << g_loglevel[level] << "][" << buf << "] ";

    slog_(args...);
}

#endif

In call function:

slog(INFO, "hello, number ", n, ", next is ", n + 1);

then compile error:

main.cpp:6:53: error: no matching function for call to 'slog(LOGLEVEL, const char [15], int&, const char [11], int)'
main.cpp:6:53: note: candidate is:
In file included from main.cpp:2:0:
slog.h:19:6: note: template<class T, class ... Args> void slog(LOGLEVEL, const Args& ...)
slog.h:19:6: note:   template argument deduction/substitution failed:
main.cpp:6:53: note:   couldn't deduce template parameter 'T'

Thanks!

Upvotes: 1

Views: 429

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

Change template <class T, class... Args> to template <class... Args> for slog. As the error message says: couldn't deduce template parameter 'T' because you never use it as a function parameter.

Upvotes: 3

Related Questions