std :: endl和variadic模板

时间:2014-01-02 09:12:18

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

代码:

#include <iostream>

void out()
{
}

template<typename T, typename... Args>
void out(T value, Args... args)
{
    std::cout << value;
    out(args...);
}

int main()
{
    out("12345", "  ", 5, "\n"); // OK
    out(std::endl);              // compilation error
    return 0;
}

构建错误:

g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -pthread -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:17:15: error: no matching function for call to ‘out(<unresolved overloaded function type>)’
../main.cpp:17:15: note: candidates are:
../main.cpp:3:6: note: void out()
../main.cpp:3:6: note:   candidate expects 0 arguments, 1 provided
../main.cpp:8:6: note: template<class T, class ... Args> void out(T, Args ...)
../main.cpp:8:6: note:   template argument deduction/substitution failed:
../main.cpp:17:15: note:   couldn't deduce template parameter ‘T’

所以除了std::endl之外,一切都还可以。我该如何解决这个问题(使用“\ n”除外)?

1 个答案:

答案 0 :(得分:12)

std::endl是一个重载函数,(在许多STL实现中,是一个模板),编译器没有关于可供选择的信息。

将其投射为static_cast<std::ostream&(*)(std::ostream&)>(std::endl)