在我的代码中,我使用可变参数模板函数 进行日志记录。但是当我使用 std::endl
作为参数时,我得到以下编译器错误:
Error: no matching function for call to 'LOG_ERROR(const char [14], int&, )' LOG_ERROR("Sum of x+y = ", z, std::endl);
note: candidate: 'void LOG_ERROR()' inline void LOG_ERROR() {
note: candidate expects 0 arguments, 3 provided
我的代码:
#include <iostream>
inline void LOG_ERROR() {
std::cout << std::endl;
}
template<typename First, typename ...Rest>
void LOG_ERROR(First && first, Rest && ...rest){
std::cout << std::forward<First>(first);
LOG_ERROR(std::forward<Rest>(rest)...);
}
int main() {
int foo=40;
LOG_ERROR("My foo = ", foo, std::endl);
}
该代码在 "\n"
下运行良好,但我很想知道为什么它在 std::endl
下失败以及如何修复它
最佳答案
长话短说 - std::endl
是函数模板,在传递时无法推导模板参数。您可以通过这种方式帮助您的编译器:
LOG_ERROR("My foo = ", foo, std::endl<char, std::char_traits<char>>);
尽管我觉得这是一段丑陋的代码,但它运行得非常完美。
关于c++ - 可变参数模板函数:没有匹配的调用函数,std::endl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51871383/