1

我用c++0x variadic templates写了一个简单的日志函数,但是有模板推导错误,谁能帮帮我,谢谢!

#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

在调用函数中:

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

然后编译错误:

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'

谢谢!

4

1 回答 1

3

更改template <class T, class... Args>template <class... Args>for slog。正如错误消息所说:couldn't deduce template parameter 'T'因为您从不将其用作函数参数。

于 2012-09-21T03:21:14.383 回答