std::endl and variadic template [duplicate]

▼魔方 西西 提交于 2019-12-23 07:47:22

问题


Code:

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

Build errors:

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’

So, everything is OK except std::endl. How can I fix this (except of using "\n")?


回答1:


std::endl is an overloaded function, (in many STL implementations, a template) and the compiler has no info about what to choose from.

Just cast it as static_cast<std::ostream&(*)(std::ostream&)>(std::endl)



来源:https://stackoverflow.com/questions/20879611/stdendl-and-variadic-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!